I found this mocking example floating around on a tutorial page, but I find it confusing that this is used as an example so often.
test("mock return value", () => {
const mock = jest.fn();
mock.mockReturnValue("bar");
expect(mock("foo")).toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
});
Does const mock = jest.fn();
ever connect to a real function that needs to be mocked? If so, how does it know which function to mock? What is the use case for a new and random mock
like this?
CodePudding user response:
The example in this article only demonstrates the functionality of jest.fn()
. The mock
object is not used by the code to be tested.
As it says, the mock function provides the below features:
- Capture calls
- Set return values
- Change the implementation
There is a scenario in real code where a function takes an object and calls a method on that object. In this scenario, you can create a mock object and pass it to that function.
E.g.
// A real function need to be tested, it can be imported from a module
function getUserById(dbc, id) {
return dbc.query('select * from users where id = $1;', [id]);
}
describe('70538368', () => {
test('should pass', () => {
const mDbc = {
query: jest.fn().mockReturnValue({ name: 'teresa teng' }),
};
const actual = getUserById(mDbc, '1');
expect(actual).toEqual({ name: 'teresa teng' });
expect(mDbc.query).toBeCalledWith('select * from users where id = $1;', ['1']);
});
});