Jest中的toMatchSnapshot时无法模拟useEffect中的函数 [英] cannot mock function in useEffect when toMatchSnapshot in Jest

查看:412
本文介绍了Jest中的toMatchSnapshot时无法模拟useEffect中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 LayoutDummy.js 上获取所有快照,以完成我的单元测试范围

I'm trying to get all snapshot on my LayoutDummy.js to complete my unit test coverage

运行测试时出现错误,它表示dummyFunc不是下面的函数

when I Run Test I got error, it says dummyFunc is not a function like below

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

I have wrote my actual code in functional component and testing file like this

LayoutDummy.js

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

test/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();
  });
});

为什么该函数无法在我的单元测试中模拟,请问是否有任何建议通过所有快照通过测试.

Why the function cannot mock in my unit test, please if there is any suggest to pass test with all snapshot.

推荐答案

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

The problem is specific to React test renderer rather than toMatchSnapshot

dummyFunc不能被模拟. dummyFunc变量是LayoutDummy功能范围的局部变量.不能在定义它们的范围之外访问局部变量.

dummyFunc cannot be mocked. dummyFunc variable is local to LayoutDummy function scope. Local variables cannot be accessed outside the scope where they were defined.

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

The test fails because useEffect works differently in test renderer rather than in DOM renderer. Normally useEffect callback would be called after the initial render but in tests it's called instantly before evaluating const dummyFunc line. There's no reason for this line to be specifically placed after useEffect. In order to not cause problems in tests it should be lifted:

  const [caption, setCaption] = useState('loading...');

  const dummyFunc = () => {
    setCaption('dummyFunc is running');
  };

  useEffect(() => {
    dummyFunc();
  }, []);

这篇关于Jest中的toMatchSnapshot时无法模拟useEffect中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆