Categories
JavaScript Answers

How to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest?

Spread the love

Sometimes, we want to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest.

In this article, we’ll look at how to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest.

How to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest?

To fix the ‘jest.fn() value must be a mock function or spy’ error with Jest, we should add a spy to the function that we’re testing.

For instance, we write

const video = require('./video');

test('plays video', () => {
  const spy = jest.spyOn(video, 'play');
  const isPlaying = video.play();

  expect(spy).toHaveBeenCalled();
  expect(isPlaying).toBe(true);

  spy.mockRestore();
});

to call jest.spyOn to spy on the play function in the video module.

Then we call play to test the play method.

And then we check the behavior of the spy with toHaveBeenCalled and check the returned result with toBe.

Finally, we call mockRestore to reset the spy.

Conclusion

To fix the ‘jest.fn() value must be a mock function or spy’ error with Jest, we should add a spy to the function that we’re testing.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *