【问题标题】:cannot mock function in useEffect when toMatchSnapshot in JestJest 中的 toMatchSnapshot 时无法在 useEffect 中模拟函数
【发布时间】:2020-10-02 20:53:47
【问题描述】:

我正在尝试获取我的 LayoutDummy.js 上的所有快照以完成我的单元测试覆盖率

当我运行测试时出现错误,它说 dummyFunc 不是下面这样的函数

我已经在这样的功能组件和测试文件中编写了我的实际代码

LayoutDummy.js

import React, { useEffect, useState } from 'react';

const LayoutDummy = () => {
  const [caption, setCaption] = useState('loading...');
  useEffect(() => {
    dummyFunc();
  }, []);

  const dummyFunc = () => {
    setCaption('dummyFunc is running');
  };
  return (
    <div>
      <p>LayoutDummy</p>
      <p>{caption}</p>
    </div>
  );
};

export default LayoutDummy;

测试/LayoutDummy.js

import React, { useEffect } from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import LayoutDummy from '../LayoutDummy';


const dummyFunc = jest.fn();

useEffect.mockImplementationOnce(fn => fn());

describe('mock func in useEffct', () => {

  test('render', () => {
    const shallow = new ShallowRenderer();
    const tree = shallow.render(<LayoutDummy />);
    dummyFunc.mockReturnValueOnce('dummyFunc is running');
    expect(tree).toMatchSnapshot();
  });
});

为什么函数不能在我的单元测试中模拟,如果有任何建议通过所有快照的测试。

【问题讨论】:

    标签: reactjs jestjs react-hooks use-effect


    【解决方案1】:

    问题是特定于 React 测试渲染器而不是 toMatchSnapshot

    dummyFunc 不能被模拟。 dummyFunc 变量是 LayoutDummy 函数范围的本地变量。不能在定义它们的范围之外访问局部变量。

    测试失败是因为useEffect 在测试渲染器中的工作方式与在 DOM 渲染器中的不同。通常useEffect 回调将在初始渲染之后调用,但在测试中它会在评估const dummyFunc 行之前立即调用。没有理由将此行专门放在useEffect 之后。为了不在测试中引起问题,应该取消它:

      const [caption, setCaption] = useState('loading...');
    
      const dummyFunc = () => {
        setCaption('dummyFunc is running');
      };
    
      useEffect(() => {
        dummyFunc();
      }, []);
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2021-05-23
      • 2022-10-05
      • 2018-09-14
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      相关资源
      最近更新 更多