cannot mock function in useEffect when toMatchSnapshot in Jest

旧巷老猫 提交于 2020-12-15 04:28:50

问题


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

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

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;

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.


回答1:


The problem is specific to React test renderer rather than toMatchSnapshot

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

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


来源:https://stackoverflow.com/questions/64165739/cannot-mock-function-in-useeffect-when-tomatchsnapshot-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!