Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Boost main graph loading time and add test coverage (#6384)
RobertJoonas23f7702e8121
diff --git a/assets/js/dashboard/components/graph.tsx b/assets/js/dashboard/components/graph.tsxindex 8a2d1ed003..85fa237437 100644--- a/assets/js/dashboard/components/graph.tsx+++ b/assets/js/dashboard/components/graph.tsx@@ -280,7 +280,8 @@ function InnerGraph<T extends GraphYValues>({svg,series,x: point.x,- y: point.values[seriesIndex]+ y: point.values[seriesIndex],+ bucketIndex: i})points[i] = {...point,@@ -800,6 +801,7 @@ function drawLine<T extends GraphYValues>({svg.append('path').attr('class', classNames(className))+ .attr('data-testid', 'graph-line').datum(datum).attr('d', line)}@@ -808,12 +810,14 @@ function drawDot({svg,series,x,- y+ y,+ bucketIndex}: {svg: SelectedSVGseries: SeriesConfigx: numbery: number | null+ bucketIndex: number}): SelectedGroup {const group = svg.append('g').attr('class', 'group')if (series.dot && y !== null) {@@ -822,6 +826,7 @@ function drawDot({.attr('r', 2.5).attr('class', series.dot.dotClassName).attr('transform', `translate(${x},${y})`)+ .attr('data-testid', `graph-dot-group-${bucketIndex}`)}return group}diff --git a/assets/js/dashboard/custom-hooks.js b/assets/js/dashboard/custom-hooks.jsindex 08db25a195..d49c74495f 100644--- a/assets/js/dashboard/custom-hooks.js+++ b/assets/js/dashboard/custom-hooks.js@@ -15,7 +15,7 @@ export function useMountedEffect(fn, deps) {}, deps)}-const DEBOUNCE_DELAY = 300+export const DEBOUNCE_DELAY = 300export function useDebounce(fn, delay = DEBOUNCE_DELAY) {const timerRef = useRef(null)diff --git a/assets/js/dashboard/stats/graph/fetch-main-graph.ts b/assets/js/dashboard/stats/graph/fetch-main-graph.tsindex 4758298232..8dff7e3bad 100644--- a/assets/js/dashboard/stats/graph/fetch-main-graph.ts+++ b/assets/js/dashboard/stats/graph/fetch-main-graph.ts@@ -11,7 +11,7 @@ import { useDashboardStateContext } from '../../dashboard-state-context'import { UseQueryResult } from '@tanstack/react-query'export function useMainGraphQuery(- metric: Metric | null,+ metric: Metric,interval: Interval): {apiState: UseQueryResult<MainGraphResponse>@@ -28,7 +28,7 @@ export function useMainGraphQuery({dashboardState,reportParams: {- metrics: [metricToQuery!],+ metrics: [metricToQuery],dimensions: [`time:${interval}`],include: {time_labels: true,@@ -43,10 +43,7 @@ export function useMainGraphQuery(const { apiState, isRealtimeSilentUpdate } = useQueryApi<MainGraphResponse>(site,mainGraphQueryKey,- {- getStatsQuery: getMainGraphQuery,- enabled: !!metric- }+ { getStatsQuery: getMainGraphQuery })return { apiState, isRealtimeSilentUpdate }diff --git a/assets/js/dashboard/stats/graph/main-graph.tsx b/assets/js/dashboard/stats/graph/main-graph.tsxindex aeb5142cee..185716925a 100644--- a/assets/js/dashboard/stats/graph/main-graph.tsx+++ b/assets/js/dashboard/stats/graph/main-graph.tsx@@ -463,9 +463,15 @@ const MainGraphTooltip = ({typeof onClick !== 'function' && 'pointer-events-none')}>- <aside className="text-sm font-normal text-gray-100 flex flex-col gap-1.5">+ <aside+ data-testid="graph-tooltip"+ className="text-sm font-normal text-gray-100 flex flex-col gap-1.5"+ ><div className="flex justify-between items-center rounded-sm">- <div className="font-semibold mr-4 text-xs uppercase whitespace-nowrap">+ <div+ data-testid="metric-label"+ className="font-semibold mr-4 text-xs uppercase whitespace-nowrap"+ >{metricLabel}</div>{comparison.isDefined && typeof change === 'number' && (@@ -481,7 +487,10 @@ const MainGraphTooltip = ({<div className="flex flex-row justify-between items-center"><div className="flex items-center mr-4"><div className="size-2 flex-none mr-2 rounded-full bg-indigo-400" />- <div className="whitespace-nowrap">+ <div+ data-testid="main-time-label"+ className="whitespace-nowrap"+ >{getFullBucketLabel(main.timeLabel, {isRealtime,interval,@@ -493,7 +502,10 @@ const MainGraphTooltip = ({})}</div></div>- <div className="font-bold whitespace-nowrap">+ <div+ data-testid="main-value"+ className="font-bold whitespace-nowrap"+ >{getFormattedValue(main.value)}</div></div>@@ -515,7 +527,10 @@ const MainGraphTooltip = ({})}</div></div>- <div className="font-bold whitespace-nowrap">+ <div+ data-testid="comparison-value"+ className="font-bold whitespace-nowrap"+ >{' '}{getFormattedValue(comparison.value)}</div>diff --git a/assets/js/dashboard/stats/graph/visitor-graph.test.tsx b/assets/js/dashboard/stats/graph/visitor-graph.test.tsxnew file mode 100644index 0000000000..8094ea497c--- /dev/null+++ b/assets/js/dashboard/stats/graph/visitor-graph.test.tsx@@ -0,0 +1,162 @@+import React from 'react'+import { render, waitForElementToBeRemoved } from '@testing-library/react'+import { TestContextProviders } from '../../../../test-utils/app-context-providers'+import VisitorGraph from './visitor-graph'+import { MockAPI } from '../../../../test-utils/mock-api'++// jsdom doesn't implement ResizeObserver (used by useMainGraphWidth and useGuessTopStatsHeight)+global.ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}++const LOADING_SPINNER = '[data-testid="loading-spinner"]'++const domain = 'dummy.site'+const queryPath = `/api/stats/${domain}/query/`+const metricStorageKey = `metric__${domain}`++// Default metrics shown in the top stats bar without any filter active+const DEFAULT_TOP_STATS_METRICS = [+ 'visitors',+ 'visits',+ 'pageviews',+ 'views_per_visit',+ 'bounce_rate',+ 'visit_duration'+]++function buildTopStatsResponse(metrics = DEFAULT_TOP_STATS_METRICS) {+ return {+ query: {+ metrics,+ dimensions: [],+ date_range: ['2024-01-01', '2024-01-28']+ },+ meta: {},+ results: [{ dimensions: [], metrics: metrics.map(() => 0) }]+ }+}++function buildMainGraphResponse(metric: string) {+ return {+ query: {+ metrics: [metric],+ dimensions: ['time:day'],+ date_range: ['2024-01-01', '2024-01-28']+ },+ meta: {+ time_labels: [],+ time_label_result_indices: [],+ partial_time_labels: null,+ comparison_partial_time_labels: null,+ empty_metrics: [0],+ present_index: 0+ },+ results: [],+ comparison_results: []+ }+}++let mockAPI: MockAPI++beforeAll(() => {+ mockAPI = new MockAPI().start()+})++afterAll(() => {+ mockAPI.stop()+})++beforeEach(() => {+ mockAPI.clear()+ localStorage.clear()+})++describe('main graph metric selection', () => {+ // sets up a single handler that returns either a top stats response (when+ // requested dimensions = []) or a graph response. Collects metrics that+ // have been requested by the graph into an array and returns it.+ function setupQueryHandler(topStatsMetrics = DEFAULT_TOP_STATS_METRICS) {+ const mainGraphCalledWithMetrics: string[] = []++ mockAPI.post(+ queryPath,+ async (_input: RequestInfo | URL, init?: RequestInit) => {+ const body = JSON.parse(init!.body as string) as {+ metrics: string[]+ dimensions: string[]+ }++ if (body.dimensions.length === 0) {+ return {+ status: 200,+ ok: true,+ json: async () => buildTopStatsResponse(topStatsMetrics)+ } as Response+ }++ const metric = body.metrics[0]+ mainGraphCalledWithMetrics.push(metric)+ return {+ status: 200,+ ok: true,+ json: async () => buildMainGraphResponse(metric)+ } as Response+ }+ )++ return { mainGraphCalledWithMetrics }+ }++ test('no stored metric → defaults to visitors, single graph request', async () => {+ const { mainGraphCalledWithMetrics } = setupQueryHandler()++ render(+ <TestContextProviders siteOptions={{ domain }}>+ <VisitorGraph />+ </TestContextProviders>+ )++ await waitForElementToBeRemoved(() =>+ document.querySelector(LOADING_SPINNER)+ )++ expect(mainGraphCalledWithMetrics).toEqual(['visitors'])+ })++ test('valid stored metric -> initial metric from storage, single graph request', async () => {+ localStorage.setItem(metricStorageKey, 'pageviews')+ const { mainGraphCalledWithMetrics } = setupQueryHandler()++ render(+ <TestContextProviders siteOptions={{ domain }}>+ <VisitorGraph />+ </TestContextProviders>+ )++ await waitForElementToBeRemoved(() =>+ document.querySelector(LOADING_SPINNER)+ )++ expect(mainGraphCalledWithMetrics).toEqual(['pageviews'])+ })++ test('invalid stored metric -> initial fetch with stored metric, corrected to default after top stats load', async () => {+ localStorage.setItem(metricStorageKey, 'scroll_depth')+ const { mainGraphCalledWithMetrics } = setupQueryHandler()++ render(+ <TestContextProviders siteOptions={{ domain }}>+ <VisitorGraph />+ </TestContextProviders>+ )++ await waitForElementToBeRemoved(() =>+ document.querySelector(LOADING_SPINNER)+ )++ expect(mainGraphCalledWithMetrics).toEqual(['scroll_depth', 'visitors'])+ })+})diff --git a/assets/js/dashboard/stats/graph/visitor-graph.tsx b/assets/js/dashboard/stats/graph/visitor-graph.tsxindex 0c866547b5..da6957ce1f 100644--- a/assets/js/dashboard/stats/graph/visitor-graph.tsx+++ b/assets/js/dashboard/stats/graph/visitor-graph.tsx@@ -11,6 +11,7 @@ import { useSetImportsIncluded } from './imports-included-context'// height of at least one row of top statsconst DEFAULT_TOP_STATS_LOADING_HEIGHT_PX = 85+const DEFAULT_GRAPH_METRIC = 'visitors'export default function VisitorGraph({updateImportedDataInView@@ -24,14 +25,8 @@ export default function VisitorGraph({const { selectedInterval } = useGraphIntervalContext()- // Possible future improvement -- currently, if there's no stored metric,- // the graph fetch doesn't run until Top Stats are loaded. That's because- // Top Stats tell us which metrics are available for the graph. However,- // as things stand today, the `visitors` metric is always available and- // could become the default selectedMetric, making it possible to fetch- // the graph instantly.- const [selectedMetric, setSelectedMetric] = useState<Metric | null>(- getStoredMetric(site)+ const [selectedMetric, setSelectedMetric] = useState<Metric>(+ getStoredMetric(site) || DEFAULT_GRAPH_METRIC)const onMetricClick = useCallback((metric: Metric) => {@@ -51,7 +46,8 @@ export default function VisitorGraph({isRealtimeSilentUpdate: isMainGraphRealtimeSilentUpdate} = useMainGraphQuery(selectedMetric, selectedInterval)- // update metric to one that exists+ // Fall back to default graph metric if the stored metric+ // does not exist in the returned Top StatsuseEffect(() => {if (topStatsApiState.data) {const availableMetrics = topStatsApiState.data.query.metrics@@ -63,7 +59,7 @@ export default function VisitorGraph({) {return currentlySelectedMetric} else {- return availableMetrics[0]+ return DEFAULT_GRAPH_METRIC}})}@@ -159,7 +155,10 @@ export default function VisitorGraph({const Loader = () => {return (- <div className="absolute inset-0 bg-white rounded-md dark:bg-gray-900 flex items-center justify-center">+ <div+ data-testid="loading-spinner"+ className="absolute inset-0 bg-white rounded-md dark:bg-gray-900 flex items-center justify-center"+ ><div className="loading"><div></div></div>diff --git a/assets/js/dashboard/stats/modals/breakdown-table.tsx b/assets/js/dashboard/stats/modals/breakdown-table.tsxindex e8f0468681..ad57e28f91 100644--- a/assets/js/dashboard/stats/modals/breakdown-table.tsx+++ b/assets/js/dashboard/stats/modals/breakdown-table.tsx@@ -102,7 +102,7 @@ const InitialLoadingSpinner = () => ()const SmallLoadingSpinner = () => (- <div className="loading sm">+ <div data-testid="small-loading-spinner" className="loading sm"><div /></div>)diff --git a/assets/js/dashboard/stats/modals/details-breakdown.test.tsx b/assets/js/dashboard/stats/modals/details-breakdown.test.tsxnew file mode 100644index 0000000000..f863c55926--- /dev/null+++ b/assets/js/dashboard/stats/modals/details-breakdown.test.tsx@@ -0,0 +1,271 @@+import React, { useState, Dispatch, SetStateAction } from 'react'+import { act, render, screen, fireEvent } from '@testing-library/react'+import { TestContextProviders } from '../../../../test-utils/app-context-providers'+import { PAGES_DETAILED_METRICS, PagesDetails } from '../pages/pages'+import { MockAPI } from '../../../../test-utils/mock-api'+import { PAGINATION_LIMIT } from '../../hooks/api-client'+import { QueryApiResponse } from '../../api'+import { StatsQuery } from '../../stats-query'+import { DEBOUNCE_DELAY } from '../../custom-hooks'++const domain = 'dummy.site'+const queryPath = `/api/stats/${domain}/query/`+const MOCK_RESPONSE_DELAY_MS = 50+const SMALL_LOADING_SPINNER_TEST_ID = 'small-loading-spinner'++function buildResponse(+ results: { dimensions: string[]; metrics: number[] }[] = []+): QueryApiResponse {+ return {+ results,+ meta: {},+ query: {+ metrics: PAGES_DETAILED_METRICS,+ dimensions: ['event:page'],+ date_range: ['2024-01-01', '2024-01-28']+ },+ extraContext: { isRealtime: false, hasConversionGoalFilter: false }+ }+}++function buildFullPage(offset: number) {+ return Array.from({ length: PAGINATION_LIMIT }, (_, i) => {+ return {+ dimensions: [`/page-${offset + i}`],+ metrics: PAGES_DETAILED_METRICS.map((_metric) => 1)+ }+ })+}++function setupQueryHandler({ delay = false } = {}) {+ const requestBodies: StatsQuery[] = []++ mockAPI.post(+ queryPath,+ async (_input: RequestInfo | URL, init?: RequestInit) => {+ const body = JSON.parse(init!.body as string) as StatsQuery+ requestBodies.push(body)++ if (delay) {+ await new Promise((resolve) =>+ setTimeout(resolve, MOCK_RESPONSE_DELAY_MS)+ )+ }++ const results = buildFullPage(body.pagination?.offset || 0)+ return {+ status: 200,+ ok: true,+ json: async () => buildResponse(results)+ } as Response+ }+ )++ return { requestBodies }+}++// TanStack Query batches React state updates via a deferred setTimeout(cb, 0).+// This fires that callback so React sees the updated query state.+function flushTanStackNotification() {+ act(() => jest.advanceTimersByTime(10))+}++// Advance timers and flush microtasks until all pending React state updates settle.+async function settle() {+ // fire the mock response delay+ act(() => jest.advanceTimersByTime(MOCK_RESPONSE_DELAY_MS + 10))+ // drain Promise chains inside TanStack Query+ await act(async () => {})+ flushTanStackNotification()+}++async function expectAndAwaitLoading() {+ flushTanStackNotification()+ expect(screen.getByTestId(SMALL_LOADING_SPINNER_TEST_ID)).toBeVisible()+ await settle()+ expect(+ screen.queryByTestId(SMALL_LOADING_SPINNER_TEST_ID)+ ).not.toBeInTheDocument()+}++function expectNotLoading() {+ flushTanStackNotification()+ expect(+ screen.queryByTestId(SMALL_LOADING_SPINNER_TEST_ID)+ ).not.toBeInTheDocument()+}++let mockAPI: MockAPI++beforeAll(() => {+ mockAPI = new MockAPI().start()+})++afterAll(() => {+ mockAPI.stop()+})++beforeEach(() => {+ mockAPI.clear()+ jest.useFakeTimers()+ const modalRoot = document.createElement('div')+ modalRoot.setAttribute('id', 'modal_root')+ document.body.appendChild(modalRoot)+})++afterEach(() => {+ jest.useRealTimers()+ document.getElementById('modal_root')?.remove()+})++function renderModal() {+ let toggle: Dispatch<SetStateAction<boolean>>++ function ToggleableModal() {+ const [open, s] = useState(false)+ toggle = s+ return open ? <PagesDetails /> : null+ }++ render(+ <TestContextProviders siteOptions={{ domain }}>+ <ToggleableModal />+ </TestContextProviders>+ )++ return {+ open: async () => {+ act(() => toggle(true))+ await settle()+ },+ close: async () => {+ act(() => toggle(false))+ await settle()+ }+ }+}++test('opening the modal for a second time with the same dashboardState gets response from cache', async () => {+ const { requestBodies } = setupQueryHandler()+ const { open, close } = renderModal()++ await open()+ expect(screen.getByText('Top pages')).toBeVisible()+ expect(requestBodies).toHaveLength(1)++ await close()+ await open()+ expect(screen.getByText('Top pages')).toBeVisible()+ expect(requestBodies).toHaveLength(1)+})++test('debounced search input adds a contains filter', async () => {+ const { requestBodies } = setupQueryHandler({ delay: true })+ const { open } = renderModal()+ await open()+ expect(screen.getByText('Top pages')).toBeVisible()++ const changeSearchInput = (value: string) => {+ fireEvent.change(screen.getByRole('textbox'), { target: { value } })+ }++ for (const s of ['/', '/b', '/bl', '/blo', '/blog']) {+ changeSearchInput(s)+ }++ act(() => jest.advanceTimersByTime(DEBOUNCE_DELAY))++ await expectAndAwaitLoading()++ expect(requestBodies).toHaveLength(2)+ expect(requestBodies[1]).toMatchObject({+ filters: [['contains', 'event:page', ['/blog'], { case_sensitive: false }]]+ })+})++test('load more button fetches the next page with correct offset', async () => {+ const { requestBodies } = setupQueryHandler({ delay: true })+ const { open } = renderModal()+ await open()++ expect(screen.getByText('Top pages')).toBeVisible()+ expect(screen.getByText('Load more')).toBeVisible()++ act(() => fireEvent.click(screen.getByText('Load more')))++ await expectAndAwaitLoading()++ expect(requestBodies).toHaveLength(2)+ expect(requestBodies[0]).toMatchObject({+ pagination: { limit: PAGINATION_LIMIT, offset: 0 }+ })+ expect(requestBodies[1]).toMatchObject({+ pagination: { limit: PAGINATION_LIMIT, offset: PAGINATION_LIMIT }+ })+})++test('clicking a column header cycles sort direction', async () => {+ const { requestBodies } = setupQueryHandler({ delay: true })+ const { open } = renderModal()+ await open()++ expect(screen.getByText('Top pages')).toBeVisible()+ expect(screen.getByRole('button', { name: /visitors/i })).toBeVisible()++ act(() => fireEvent.click(screen.getByRole('button', { name: /visitors/i })))++ await expectAndAwaitLoading()++ expect(requestBodies).toHaveLength(2)+ expect(requestBodies[0]).toMatchObject({+ order_by: [+ ['visitors', 'desc'],+ ['event:page', 'asc']+ ]+ })+ expect(requestBodies[1]).toMatchObject({+ order_by: [+ ['visitors', 'asc'],+ ['event:page', 'asc']+ ]+ })+})++test('toggling sort back to the original direction gets results from cache', async () => {+ const { requestBodies } = setupQueryHandler({ delay: true })+ const { open } = renderModal()+ await open()++ expect(screen.getByRole('button', { name: /visitors/i })).toBeVisible()++ act(() => fireEvent.click(screen.getByRole('button', { name: /visitors/i })))+ await expectAndAwaitLoading()+ expect(requestBodies).toHaveLength(2)++ // cache hit — no loading spinner, no request made+ act(() => fireEvent.click(screen.getByRole('button', { name: /visitors/i })))+ expectNotLoading()+ expect(requestBodies).toHaveLength(2)+})++test('clearing search gets results from cache', async () => {+ const { requestBodies } = setupQueryHandler({ delay: true })+ const { open } = renderModal()+ await open()++ expect(screen.getByText('Top pages')).toBeVisible()++ const changeSearchInput = (value: string) => {+ fireEvent.change(screen.getByRole('textbox'), { target: { value } })+ }++ changeSearchInput('/blog')+ act(() => jest.advanceTimersByTime(DEBOUNCE_DELAY))+ await expectAndAwaitLoading()+ expect(requestBodies).toHaveLength(2)++ changeSearchInput('')+ act(() => jest.advanceTimersByTime(DEBOUNCE_DELAY))+ expectNotLoading()+ expect(requestBodies).toHaveLength(2)+})diff --git a/assets/js/dashboard/stats/pages/pages.tsx b/assets/js/dashboard/stats/pages/pages.tsxindex 43a7d135cf..4f27cf3645 100644--- a/assets/js/dashboard/stats/pages/pages.tsx+++ b/assets/js/dashboard/stats/pages/pages.tsx@@ -17,7 +17,7 @@ import { getBreakdownMetrics } from '../breakdowns'export const PAGES_BAR_COLOR = 'bg-orange-50 group-hover/row:bg-orange-100'const DIMENSION = 'event:page'-const DETAILED_METRICS: Metric[] = [+export const PAGES_DETAILED_METRICS: Metric[] = ['visitors','percentage','pageviews',@@ -77,7 +77,7 @@ export function PagesDetails() {isRealtime: isRealTimeDashboard(dashboardState),isDetailed: true,isRevenueAvailable: isRevenueAvailable,- detailedMetrics: DETAILED_METRICS+ detailedMetrics: PAGES_DETAILED_METRICS})const getExternalLinkUrl = useCallback(diff --git a/assets/test-utils/mock-api.ts b/assets/test-utils/mock-api.tsindex 3856162181..91a597eb2e 100644--- a/assets/test-utils/mock-api.ts+++ b/assets/test-utils/mock-api.ts@@ -23,6 +23,22 @@ export class MockAPI {public get(urlWithoutQueryString: string,responseHandler: typeof fetch | Record<string, unknown> | number | null+ ): jest.Mock {+ return this.register('get', urlWithoutQueryString, responseHandler)+ }++ // sets post handler+ public post(+ urlWithoutQueryString: string,+ responseHandler: typeof fetch | Record<string, unknown>+ ): jest.Mock {+ return this.register('post', urlWithoutQueryString, responseHandler)+ }++ private register(+ method: string,+ urlWithoutQueryString: string,+ responseHandler: typeof fetch | Record<string, unknown> | number | null): jest.Mock {const handler: typeof fetch =typeof responseHandler === 'function'@@ -36,7 +52,7 @@ export class MockAPI {} as Response))const jestWrappedHandler = jest.fn(handler)- this.setHandler('get', urlWithoutQueryString, jestWrappedHandler)+ this.setHandler(method, urlWithoutQueryString, jestWrappedHandler)return jestWrappedHandler}@@ -55,7 +71,7 @@ export class MockAPI {if (typeof input !== 'string') {throw new Error(`Unmocked request ${input.toString()}`)}- const method = init?.method ?? 'get'+ const method = (init?.method ?? 'get').toLowerCase()const urlWithoutQueryString = input.split('?')[0]const handler = this.getHandler(method, urlWithoutQueryString)if (!handler) {diff --git a/e2e/package.json b/e2e/package.jsonindex ab45435c7d..444224e85d 100644--- a/e2e/package.json+++ b/e2e/package.json@@ -2,6 +2,7 @@"name": "e2e","scripts": {"lint": "eslint",+ "format": "prettier --write \"**/*.{js,mjs,ts,html,json,md}\"","check-format": "prettier --check \"**/*.{js,mjs,ts,html,json,md}\"","typecheck": "tsc --noEmit --pretty","test": "npx playwright test"diff --git a/e2e/tests/dashboard/main-graph.spec.ts b/e2e/tests/dashboard/main-graph.spec.tsnew file mode 100644index 0000000000..06888b002c--- /dev/null+++ b/e2e/tests/dashboard/main-graph.spec.ts@@ -0,0 +1,400 @@+import { test, expect, type Page } from '@playwright/test'+import { setupSite, populateStats, addGoal } from '../fixtures'++type MetricCase = {+ selector: string+ expectedMetricLabel: string+ expectedBuckets: BucketExpectation[]+}+type BucketExpectation = [+ bucketIndex: number,+ timeLabel: string,+ metricValue: string+]++const MAIN_LINE = 'path.stroke-indigo-500[data-testid="graph-line"]'++async function hoverAndReadTooltip(page: Page, bucketIndex: number) {+ await page+ .locator(`[data-testid="graph-dot-group-${bucketIndex}"]`)+ .first()+ .hover()+ const tooltip = page.locator('[data-testid="graph-tooltip"]')+ await expect(tooltip).toBeVisible()+ return {+ metricLabel: await tooltip+ .locator('[data-testid="metric-label"]')+ .innerText(),+ mainTimeLabel: await tooltip+ .locator('[data-testid="main-time-label"]')+ .innerText(),+ mainValue: await tooltip.locator('[data-testid="main-value"]').innerText()+ }+}++test.describe('plotting all metrics', () => {+ // Time label rendering depends on locale. Set it to one with 24h clock+ test.use({ locale: 'en-GB' })++ test('default view', async ({ page, request }) => {+ const { domain } = await setupSite({ page, request })++ await populateStats({+ request,+ domain,+ events: [+ {+ user_id: 1,+ name: 'pageview',+ pathname: '/',+ timestamp: '2021-01-01 00:00:00'+ },+ {+ user_id: 1,+ name: 'pageview',+ pathname: '/page1',+ timestamp: '2021-01-01 00:10:00'+ },+ {+ user_id: 1,+ name: 'pageview',+ pathname: '/page2',+ timestamp: '2021-01-01 00:20:00'+ },+ {+ user_id: 2,+ name: 'pageview',+ pathname: '/',+ timestamp: '2021-01-01 05:00:00'+ }+ ]+ })++ await page.goto('/' + domain + '?period=day&date=2021-01-01', {+ waitUntil: 'commit'+ })++ const graphLine = page.locator(MAIN_LINE)+ await expect(graphLine).toBeVisible()++ const metricCases: MetricCase[] = [+ {+ selector: '#visitors',+ expectedMetricLabel: 'UNIQUE VISITORS',+ expectedBuckets: [+ [0, '00:00', '1'],+ [1, '01:00', '0'],+ [5, '05:00', '1']+ ]+ },+ {+ selector: '#visits',+ expectedMetricLabel: 'TOTAL VISITS',+ expectedBuckets: [+ [0, '00:00', '1'],+ [1, '01:00', '0'],+ [5, '05:00', '1']+ ]+ },+ {+ selector: '#pageviews',+ expectedMetricLabel: 'TOTAL PAGEVIEWS',+ expectedBuckets: [+ [0, '00:00', '3'],+ [1, '01:00', '0'],+ [5, '05:00', '1']+ ]+ },+ {+ selector: '#views_per_visit',+ expectedMetricLabel: 'VIEWS PER VISIT',+ expectedBuckets: [+ [0, '00:00', '3'],+ [1, '01:00', '0'],+ [5, '05:00', '1']+ ]+ },+ {+ selector: '#bounce_rate',+ expectedMetricLabel: 'BOUNCE RATE',+ expectedBuckets: [+ [0, '00:00', '0%'],+ [1, '01:00', '0%'],+ [5, '05:00', '100%']+ ]+ },+ {+ selector: '#visit_duration',+ expectedMetricLabel: 'VISIT DURATION',+ expectedBuckets: [+ [0, '00:00', '20m 00s'],+ [1, '01:00', '-'],+ [5, '05:00', '0s']+ ]+ }+ ]++ for (const {+ selector,+ expectedMetricLabel,+ expectedBuckets+ } of metricCases) {+ await test.step(expectedMetricLabel, async () => {+ await page.locator(selector).click()+ await expect(graphLine).toBeVisible()++ for (const [bucketIndex, timeLabel, metricValue] of expectedBuckets) {+ const tooltipInfo = await hoverAndReadTooltip(page, bucketIndex)+ expect(tooltipInfo.metricLabel).toBe(expectedMetricLabel)+ expect(+ tooltipInfo.mainTimeLabel,+ `Wrong time label for ${expectedMetricLabel}`+ ).toBe(timeLabel)+ expect(+ tooltipInfo.mainValue,+ `Wrong metric value for ${expectedMetricLabel} in ${timeLabel}`+ ).toBe(metricValue)+ }+ })+ }+ })++ test('goal-filtered view', async ({ page, request }) => {+ const goalName = 'Signup'+ const { domain } = await setupSite({ page, request })++ await addGoal({ request, domain, params: { event_name: goalName } })++ await populateStats({+ request,+ domain,+ events: [+ {+ user_id: 1,+ name: 'pageview',+ timestamp: '2021-01-01 00:00:00'+ },+ {+ user_id: 2,+ name: goalName,+ timestamp: '2021-01-01 10:00:00'+ },+ {+ user_id: 2,+ name: goalName,+ timestamp: '2021-01-01 10:10:00'+ },+ {+ user_id: 4,+ name: 'pageview',+ timestamp: '2021-01-01 10:00:00'+ },+ {+ user_id: 5,+ name: goalName,+ timestamp: '2021-01-01 23:00:00'+ }+ ]+ })++ await page.goto(+ '/' + domain + '?period=day&date=2021-01-01&f=is,goal,Signup',+ { waitUntil: 'commit' }+ )++ const graphLine = page.locator(MAIN_LINE)+ await expect(graphLine).toBeVisible()++ const metricCases: MetricCase[] = [+ {+ selector: '#visitors',+ expectedMetricLabel: 'UNIQUE CONVERSIONS',+ expectedBuckets: [+ [0, '00:00', '0'],+ [1, '01:00', '0'],+ [10, '10:00', '1'],+ [23, '23:00', '1']+ ]+ },+ {+ selector: '#events',+ expectedMetricLabel: 'TOTAL CONVERSIONS',+ expectedBuckets: [+ [0, '00:00', '0'],+ [1, '01:00', '0'],+ [10, '10:00', '2'],+ [23, '23:00', '1']+ ]+ },+ {+ selector: '#conversion_rate',+ expectedMetricLabel: 'CONVERSION RATE',+ expectedBuckets: [+ [0, '00:00', '0%'],+ [1, '01:00', '0%'],+ [10, '10:00', '50%'],+ [23, '23:00', '100%']+ ]+ }+ ]++ for (const {+ selector,+ expectedMetricLabel,+ expectedBuckets+ } of metricCases) {+ await test.step(expectedMetricLabel, async () => {+ await page.locator(selector).click()+ await expect(graphLine).toBeVisible()++ for (const [bucketIndex, timeLabel, metricValue] of expectedBuckets) {+ const tooltipInfo = await hoverAndReadTooltip(page, bucketIndex)+ expect(tooltipInfo.metricLabel).toBe(expectedMetricLabel)+ expect(+ tooltipInfo.mainTimeLabel,+ `Wrong time label for ${expectedMetricLabel}`+ ).toBe(timeLabel)+ expect(+ tooltipInfo.mainValue,+ `Wrong metric value for ${expectedMetricLabel} in ${timeLabel}`+ ).toBe(metricValue)+ }+ })+ }+ })++ test('page-filtered view', async ({ page, request }) => {+ const { domain } = await setupSite({ page, request })++ await populateStats({+ request,+ domain,+ events: [+ {+ user_id: 1,+ name: 'pageview',+ pathname: '/one',+ timestamp: '2021-01-01 00:00:00'+ },+ {+ user_id: 2,+ name: 'pageview',+ pathname: '/one',+ timestamp: '2021-01-01 05:30:00'+ },+ {+ user_id: 2,+ name: 'engagement',+ pathname: '/one',+ scroll_depth: 90,+ engagement_time: 20 * 60 * 1000,+ timestamp: '2021-01-01 05:50:00'+ },+ {+ user_id: 2,+ name: 'pageview',+ pathname: '/two',+ timestamp: '2021-01-01 05:50:00'+ },+ {+ user_id: 3,+ pathname: '/two',+ name: 'pageview',+ timestamp: '2021-01-01 00:00:00'+ }+ ]+ })++ await page.goto(+ '/' + domain + '?period=day&date=2021-01-01&f=is,page,/one',+ { waitUntil: 'commit' }+ )++ const graphLine = page.locator(MAIN_LINE)+ await expect(graphLine).toBeVisible()++ const metricCases: MetricCase[] = [+ {+ selector: '#visitors',+ expectedMetricLabel: 'UNIQUE VISITORS',+ expectedBuckets: [+ [0, '00:00', '1'],+ [5, '05:00', '1'],+ [10, '10:00', '0']+ ]+ },+ {+ selector: '#visits',+ expectedMetricLabel: 'TOTAL VISITS',+ expectedBuckets: [+ [0, '00:00', '1'],+ [5, '05:00', '1'],+ [10, '10:00', '0']+ ]+ },+ {+ selector: '#pageviews',+ expectedMetricLabel: 'TOTAL PAGEVIEWS',+ expectedBuckets: [+ [0, '00:00', '1'],+ [5, '05:00', '1'],+ [10, '10:00', '0']+ ]+ },+ {+ selector: '#bounce_rate',+ expectedMetricLabel: 'BOUNCE RATE',+ expectedBuckets: [+ [0, '00:00', '100%'],+ [5, '05:00', '0%'],+ [10, '10:00', '0%']+ ]+ },+ {+ selector: '#scroll_depth',+ expectedMetricLabel: 'SCROLL DEPTH',+ expectedBuckets: [+ [0, '00:00', '-'],+ [5, '05:00', '90%'],+ [10, '10:00', '-']+ ]+ },+ {+ selector: '#time_on_page',+ expectedMetricLabel: 'TIME ON PAGE',+ expectedBuckets: [+ [0, '00:00', '-'],+ [5, '05:00', '20m 00s'],+ [10, '10:00', '-']+ ]+ }+ ]++ for (const {+ selector,+ expectedMetricLabel,+ expectedBuckets+ } of metricCases) {+ await test.step(expectedMetricLabel, async () => {+ await page.locator(selector).click()+ await expect(+ graphLine,+ `Graph not visible after clicking ${selector}`+ ).toBeVisible()++ for (const [bucketIndex, timeLabel, metricValue] of expectedBuckets) {+ const tooltipInfo = await hoverAndReadTooltip(page, bucketIndex)+ expect(tooltipInfo.metricLabel).toBe(expectedMetricLabel)+ expect(+ tooltipInfo.mainTimeLabel,+ `Wrong time label for ${expectedMetricLabel}`+ ).toBe(timeLabel)+ expect(+ tooltipInfo.mainValue,+ `Wrong metric value for ${expectedMetricLabel} in ${timeLabel}`+ ).toBe(metricValue)+ }+ })+ }+ })+})diff --git a/e2e/tests/fixtures.ts b/e2e/tests/fixtures.tsindex 42b41c9310..0d15f21b93 100644--- a/e2e/tests/fixtures.ts+++ b/e2e/tests/fixtures.ts@@ -21,6 +21,7 @@ type Event = {name: stringuser_id?: numberscroll_depth?: number+ engagement_time?: numberrevenue_reporting_amount?: stringrevenue_reporting_currency?: stringpathname?: string