Skip to content

Commit

Permalink
Fix and align data source tests
Browse files Browse the repository at this point in the history
  • Loading branch information
arminmeh committed Jan 29, 2025
1 parent 852c44d commit 1994bb9
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,6 @@ describe('<DataGridPremium /> - Data source aggregation', () => {

it('should not show aggregation option in the column menu when no aggregation function is defined', async () => {
const { user } = render(<TestDataSourceAggregation aggregationFunctions={{}} />);
await waitFor(() => {
expect(getRowsSpy.callCount).to.be.greaterThan(0);
});
await user.click(within(getColumnHeaderCell(0)).getByLabelText('Menu'));
expect(screen.queryByLabelText('Aggregation')).to.equal(null);
});
Expand All @@ -120,9 +117,6 @@ describe('<DataGridPremium /> - Data source aggregation', () => {
}}
/>,
);
await waitFor(() => {
expect(getRowsSpy.callCount).to.be.greaterThan(0);
});
expect(getRowsSpy.args[0][0].aggregationModel).to.deep.equal({ id: 'size' });
});

Expand Down
75 changes: 39 additions & 36 deletions packages/x-data-grid-pro/src/tests/dataSource.DataGridPro.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,49 @@ import { useMockServer } from '@mui/x-data-grid-generator';
import { act, createRenderer, waitFor } from '@mui/internal-test-utils';
import { expect } from 'chai';
import { RefObject } from '@mui/x-internals/types';
import useLazyRef from '@mui/utils/useLazyRef';
import {
DataGridPro,
DataGridProProps,
GridApi,
GridDataSource,
GridDataSourceCache,
GridGetRowsParams,
GridGetRowsResponse,
useGridApiRef,
} from '@mui/x-data-grid-pro';
import { SinonStub, spy, stub } from 'sinon';
import { spy } from 'sinon';
import { describeSkipIf, isJSDOM } from 'test/utils/skipIf';
import { getKeyDefault } from '../hooks/features/dataSource/cache';

const cache = new Map<string, GridGetRowsResponse>();
class TestCache {
private cache: Map<string, GridGetRowsResponse>;

const testCache: GridDataSourceCache = {
set: (key, value) => cache.set(getKeyDefault(key), value),
get: (key) => cache.get(getKeyDefault(key)),
clear: () => cache.clear(),
};
constructor() {
this.cache = new Map();
}

set(key: GridGetRowsParams, value: GridGetRowsResponse) {
this.cache.set(getKeyDefault(key), value);
}
get(key: GridGetRowsParams) {
return this.cache.get(getKeyDefault(key));
}
size() {
return this.cache.size;
}
clear() {
this.cache.clear();
}
}

const pageSizeOptions = [10, 20];
const serverOptions = { useCursorPagination: false, minDelay: 0, maxDelay: 0, verbose: false };

// Needs layout
describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
const { render } = createRenderer();
const fetchRowsSpy = spy();

let apiRef: RefObject<GridApi | null>;
let fetchRowsSpy: SinonStub;
let mockServer: ReturnType<typeof useMockServer>;

function TestDataSource(props: Partial<DataGridProProps> & { shouldRequestsFail?: boolean }) {
Expand All @@ -45,18 +56,11 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
props.shouldRequestsFail ?? false,
);

// Reuse the same stub between rerenders to properly count the calls
fetchRowsSpy = useLazyRef(() => stub()).current;
const { fetchRows } = mockServer;

const originalFetchRows = mockServer.fetchRows;
const fetchRows = React.useMemo<typeof originalFetchRows>(() => {
const dataSource: GridDataSource = React.useMemo(() => {
fetchRowsSpy.resetHistory();
fetchRowsSpy.callsFake(originalFetchRows);
return (...args) => fetchRowsSpy(...args);
}, [originalFetchRows]);

const dataSource: GridDataSource = React.useMemo(
() => ({
return {
getRows: async (params: GridGetRowsParams) => {
const urlParams = new URLSearchParams({
filterModel: JSON.stringify(params.filterModel),
Expand All @@ -65,18 +69,17 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
end: `${params.end}`,
});

const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
const url = `https://mui.com/x/api/data-grid?${urlParams.toString()}`;
fetchRowsSpy(url);
const getRowsResponse = await fetchRows(url);

return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
},
}),
[fetchRows],
);
};
}, [fetchRows]);

return (
<div style={{ width: 300, height: 300 }}>
Expand All @@ -94,11 +97,6 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
);
}

// eslint-disable-next-line mocha/no-top-level-hooks
beforeEach(() => {
cache.clear();
});

it('should fetch the data on initial render', async () => {
render(<TestDataSource />);
await waitFor(() => {
Expand Down Expand Up @@ -186,14 +184,16 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
});

it('should cache the data using the custom cache', async () => {
const testCache = new TestCache();
render(<TestDataSource unstable_dataSourceCache={testCache} />);
await waitFor(() => {
expect(fetchRowsSpy.callCount).to.equal(1);
});
expect(cache.size).to.equal(1);
expect(testCache.size()).to.equal(1);
});

it('should cache the data in the chunks defined by the minimum page size', async () => {
const testCache = new TestCache();
render(
<TestDataSource
unstable_dataSourceCache={testCache}
Expand All @@ -203,10 +203,11 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
await waitFor(() => {
expect(fetchRowsSpy.callCount).to.equal(1);
});
expect(cache.size).to.equal(2); // 2 chunks of 10 rows
expect(testCache.size()).to.equal(2); // 2 chunks of 10 rows
});

it('should use the cached data when the same query is made again', async () => {
const testCache = new TestCache();
const pageChangeSpy = spy();
render(
<TestDataSource
Expand All @@ -217,7 +218,7 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
await waitFor(() => {
expect(fetchRowsSpy.callCount).to.equal(1);
});
expect(cache.size).to.equal(1);
expect(testCache.size()).to.equal(1);
expect(pageChangeSpy.callCount).to.equal(0);

act(() => {
Expand All @@ -227,7 +228,9 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
await waitFor(() => {
expect(fetchRowsSpy.callCount).to.equal(2);
});
expect(cache.size).to.equal(2);
await waitFor(() => {
expect(testCache.size()).to.equal(2);
});
expect(pageChangeSpy.callCount).to.equal(1);

act(() => {
Expand All @@ -237,7 +240,7 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source', () => {
await waitFor(() => {
expect(fetchRowsSpy.callCount).to.equal(2);
});
expect(cache.size).to.equal(2);
expect(testCache.size()).to.equal(2);
expect(pageChangeSpy.callCount).to.equal(2);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,17 @@ import {
GridGetRowsResponse,
useGridApiRef,
} from '@mui/x-data-grid-pro';
import { SinonStub, stub } from 'sinon';
import { spy } from 'sinon';
import { describeSkipIf, isJSDOM } from 'test/utils/skipIf';
import useLazyRef from '@mui/utils/useLazyRef';

// Needs layout
describeSkipIf(isJSDOM)('<DataGridPro /> - Data source lazy loader', () => {
const { render } = createRenderer();
const defaultTransformGetRowsResponse = (response: GridGetRowsResponse) => response;
const fetchRowsSpy = spy();

let transformGetRowsResponse: (response: GridGetRowsResponse) => GridGetRowsResponse;
let apiRef: RefObject<GridApi | null>;
let fetchRowsSpy: SinonStub;
let mockServer: ReturnType<typeof useMockServer>;

function TestDataSourceLazyLoader(props: Partial<DataGridProProps>) {
Expand All @@ -34,18 +33,11 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source lazy loader', () => {
{ useCursorPagination: false, minDelay: 0, maxDelay: 0, verbose: false },
);

// Reuse the same stub between rerenders to properly count the calls
fetchRowsSpy = useLazyRef(() => stub()).current;
const { fetchRows } = mockServer;

const originalFetchRows = mockServer.fetchRows;
const fetchRows = React.useMemo<typeof originalFetchRows>(() => {
const dataSource: GridDataSource = React.useMemo(() => {
fetchRowsSpy.resetHistory();
fetchRowsSpy.callsFake(originalFetchRows);
return (...args) => fetchRowsSpy(...args);
}, [originalFetchRows]);

const dataSource: GridDataSource = React.useMemo(
() => ({
return {
getRows: async (params: GridGetRowsParams) => {
const urlParams = new URLSearchParams({
filterModel: JSON.stringify(params.filterModel),
Expand All @@ -54,19 +46,18 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source lazy loader', () => {
end: `${params.end}`,
});

const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
const url = `https://mui.com/x/api/data-grid?${urlParams.toString()}`;
fetchRowsSpy(url);
const getRowsResponse = await fetchRows(url);

const response = transformGetRowsResponse(getRowsResponse);
return {
rows: response.rows,
rowCount: response.rowCount,
};
},
}),
[fetchRows],
);
};
}, [fetchRows]);

return (
<div style={{ width: 300, height: 300 }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ import {
GridGroupNode,
useGridApiRef,
} from '@mui/x-data-grid-pro';
import { SinonStub, stub } from 'sinon';
import { spy } from 'sinon';
import { getCell } from 'test/utils/helperFn';
import { describeSkipIf, isJSDOM } from 'test/utils/skipIf';
import useLazyRef from '@mui/utils/useLazyRef';

const dataSetOptions = {
dataSet: 'Employee' as const,
Expand All @@ -31,28 +30,21 @@ const serverOptions = { minDelay: 0, maxDelay: 0, verbose: false };
// Needs layout
describeSkipIf(isJSDOM)('<DataGridPro /> - Data source tree data', () => {
const { render } = createRenderer();
const fetchRowsSpy = spy();

let apiRef: RefObject<GridApi | null>;
let fetchRowsSpy: SinonStub;
let mockServer: ReturnType<typeof useMockServer>;

function TestDataSource(props: Partial<DataGridProProps> & { shouldRequestsFail?: boolean }) {
apiRef = useGridApiRef();
mockServer = useMockServer(dataSetOptions, serverOptions, props.shouldRequestsFail ?? false);
const { columns } = mockServer;

// Reuse the same stub between rerenders to properly count the calls
fetchRowsSpy = useLazyRef(() => stub()).current;
const { fetchRows } = mockServer;

const originalFetchRows = mockServer.fetchRows;
const fetchRows = React.useMemo<typeof originalFetchRows>(() => {
const dataSource: GridDataSource = React.useMemo(() => {
fetchRowsSpy.resetHistory();
fetchRowsSpy.callsFake(originalFetchRows);
return (...args) => fetchRowsSpy(...args);
}, [originalFetchRows]);

const dataSource: GridDataSource = React.useMemo(
() => ({
return {
getRows: async (params: GridGetRowsParams) => {
const urlParams = new URLSearchParams({
paginationModel: JSON.stringify(params.paginationModel),
Expand All @@ -61,9 +53,9 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source tree data', () => {
groupKeys: JSON.stringify(params.groupKeys),
});

const getRowsResponse = await fetchRows(
`https://mui.com/x/api/data-grid?${urlParams.toString()}`,
);
const url = `https://mui.com/x/api/data-grid?${urlParams.toString()}`;
fetchRowsSpy(url);
const getRowsResponse = await fetchRows(url);

return {
rows: getRowsResponse.rows,
Expand All @@ -72,9 +64,8 @@ describeSkipIf(isJSDOM)('<DataGridPro /> - Data source tree data', () => {
},
getGroupKey: (row) => row[dataSetOptions.treeData.groupingField],
getChildrenCount: (row) => row.descendantCount,
}),
[fetchRows],
);
};
}, [fetchRows]);

return (
<div style={{ width: 300, height: 300 }}>
Expand Down

0 comments on commit 1994bb9

Please sign in to comment.