cannot mock function in useEffect when toMatchSnapshot in Jest

1.3k Views Asked by At

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

enter image description here

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

There are 1 best solutions below

0
On BEST ANSWER

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