开玩笑的模拟不适用于React Testing Library

时间:2020-10-09 07:07:37

标签: javascript jestjs mocking react-testing-library

我正在使用@testing-library/react测试UI组件。无法开玩笑的模拟游戏。

似乎无法模拟导出函数getDomElement的实现,但调用了实际实现。

Table.test.js的实现

describe('Table', () => {
  jest.mock('../../../../commonHelpers/getDomElement.js', () => {});

  it('it renders columns', () => {
    render(
      <ThemeProvider>
        <Table
          columns={columns}
          data={data}         
        />
      </ThemeProvider>,
    );
  })
})

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;

getDomElement.js的实现,它通过给定的ID返回dom元素。

export default function getDomElement(id) {
  return document.getElementById(id);
}

测试结果:

const width = getDomElement('project-list').clientWidth;

TypeError: Cannot read property 'clientWidth' of null

2 个答案:

答案 0 :(得分:1)

尝试一下:

import * as myModule from '../../../../commonHelpers/getDomElement';
describe('Table', () => {
  jest.spyOn(myModule, "getDomElement").mockImplementation(() => {});
  it('it renders columns', () => {
    render(
      <ThemeProvider>
        <Table
          columns={columns}
          data={data}         
        />
      </ThemeProvider>,
    );
  })
})

答案 1 :(得分:0)

做了以下两件事,让它对我有用。

  1. 添加 __esModule:true 为我解决了这个问题。

    jest.mock('module',()=>({ __esModule: true, default: jest.fn() }));

  2. 在描述之前移动模拟部分。 (就在导入之后。)

    //移动到describe之前 -> jest.mock(...); describe('', ...);

希望这对某人有所帮助。