matcher error: received value must be a mock or spy function
The error “received value must be a mock or spy function” typically occurs when using a testing library, such as Jest or Jasmine, and trying to assert a certain behavior on a function that is not being mocked or spied on.
These libraries allow you to create mock functions or spies to test how functions are called and their returned values. Matchers are used to assert certain conditions on these mocked or spied functions.
Here’s an example to illustrate the error:
const myFunction = () => {
return 'Hello World';
};
test('should call myFunction', () => {
const receivedValue = myFunction();
expect(receivedValue).toHaveBeenCalled();
});
In this example, we have a simple function myFunction
that returns a string. The test is attempting to assert that this function has been called using the toHaveBeenCalled()
matcher. However, since we haven’t mocked or spied on myFunction
, we encounter the “received value must be a mock or spy function” error.
To fix this error, we need to either mock or spy on myFunction
before asserting its behavior. For example:
const myFunction = jest.fn(() => {
return 'Hello World';
});
test('should call myFunction', () => {
myFunction();
expect(myFunction).toHaveBeenCalled();
});
In this updated example, we’ve used Jest’s jest.fn()
method to create a mock function for myFunction
. The test now asserts that the mock function has been called using expect(myFunction).toHaveBeenCalled()
, and the error should no longer occur.
By properly mocking or spying on functions, and using the appropriate matchers, you can ensure that your tests accurately reflect the expected behavior of your code.