I am using @testing-library/react for testing UI components. Cannot get jest mock working.
It seems it cannot mock the implementation of the exported function getDomElement but actual implementation is called.
Implementation of Table.test.js
describe('Table', () => {
jest.mock('../../../../commonHelpers/getDomElement.js', () => {});
it('it renders columns', () => {
render(
<ThemeProvider>
<Table
columns={columns}
data={data}
/>
</ThemeProvider>,
);
})
})
Implementation of Table.js
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import {
useTable,
useSortBy,
useBlockLayout,
useResizeColumns,
usePagination,
} from 'react-table';
import { TableStyled as Table, TableContainer } from './styled';
import Pagination from './Pagination';
import Head from './Head';
import Body from './Body';
import TableContext from './TableContext';
const Table = ({
columns,
data,
onChangeSort,
fetchData,
pageCount: calculatedPageCount,
initialPageSize,
}) => {
const tableInstance = useTable(
{
columns,
data,
manualSortBy: true,
disableSortRemove: false,
manualPagination: true,
pageCount: calculatedPageCount,
initialState: { pageIndex: 0, pageSize: initialPageSize },
},
useSortBy,
useBlockLayout,
useResizeColumns,
usePagination,
);
const {
getTableProps,
state: { pageIndex, pageSize },
} = tableInstance;
useEffect(() => {
fetchData({ pageIndex, pageSize });
}, [fetchData, pageIndex, pageSize]);
return (
<TableContext.Provider value={tableInstance}>
<TableContainer>
<Table {...getTableProps()}>
<Head onChangeSort={onChangeSort} />
<Body />
</Table>
</TableContainer>
<Pagination />
</TableContext.Provider>
);
};
Table.propTypes = {
columns: PropTypes.array,
data: PropTypes.array,
onChangeSort: PropTypes.func,
fetchData: PropTypes.func,
pageCount: PropTypes.number,
initialPageSize: PropTypes.number,
};
export default Table;
Implementation of getDomElement.js which returns the dom element by given id.
export default function getDomElement(id) {
return document.getElementById(id);
}
Test results in:
const width = getDomElement('project-list').clientWidth;
TypeError: Cannot read property 'clientWidth' of null
TableandgetDomElementimplementations.jest.mockonly works when it is in jestsetup.js. When I move the same to a test file it doesn't work. It only started to happen when I moved to@testing-library/react