简体   繁体   English

Jest mock 不与 React 测试库一起使用

[英]Jest mock not working with React Testing Library

I am using @testing-library/react for testing UI components.我正在使用@testing-library/react来测试 UI 组件。 Cannot get jest mock working.无法开玩笑地模拟工作。

It seems it cannot mock the implementation of the exported function getDomElement but actual implementation is called.它似乎无法模拟导出的 function getDomElement的实现,但调用了实际实现。

Implementation of Table.test.js 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 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. getDomElement.js 的实现,它通过给定的 id 返回 dom 元素。

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

Try this:试试这个:

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>,
    );
  })
})

Doing following two thing, got it working for me.做以下两件事,让它为我工作。

  1. Adding __esModule:true fixed this issue for me.添加__esModule:true为我解决了这个问题。

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

  2. Moving the mocking part before the describe.在描述之前移动 mocking 部分。 (Just after the imports.) (就在进口之后。)

    //moving it to before the describe -> jest.mock(...); describe('', ...); // 将其移动到描述之前 -> jest.mock(...); describe('', ...); jest.mock(...); describe('', ...);

Hope this helps somebody.希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React 测试库 + Jest 模拟测试函数 - How to mock functions for testing using the React Testing Library + Jest MonacoEditor 不使用 Jest 和 React 测试库 - MonacoEditor not working with Jest and React Testing Library 在反应应用程序上使用 jest 和测试库未调用模拟函数 - Mock function not being called using jest and testing library on react app 使用纯 Jest 库(无酶)测试反应形式不起作用 - testing a react form with pure Jest library (no enzyme) not working 反应测试库 jest.fn() toHaveBeenCalled() 不工作 - React Testing Library jest.fn() toHaveBeenCalled() not working Jest + React:IntersectionObserver 模拟不起作用? - Jest + React: IntersectionObserver mock not working? 如何使用 Jest/react 测试库模拟带有道具的复杂反应组件 - How to mock a complex react component with props using Jest/ react testing library 用于 react-select 或 react-testing-library on change 的 Jest mock 不触发目标更改 - Jest mock for react-select or react-testing-library on change not firing on target change 如何使用 jest、react-testing-library 在 React 中模拟元素上的点击事件 - How to mock a click event on an element in React using jest , react-testing-library React:如何模拟 Auth0 以使用 Jest 进行测试 - React: How to mock Auth0 for testing with Jest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM