Here is my function
//functions.js
const functions =
{
add: (a, b) => a + b,
average: (a, b) => functions.add(a, b) / 2
}
module.exports = functions;
Here goes my test,
jest.mock("./functions"); // this happens automatically with automocking
const functions = require("./functions");
test('calculate the average', () => {
functions.add.mockImplementation((a, b) => a + b);
expect(functions.average(2, 2)).toBe(2);
})
I know how to do it on NestJS, at least for the context I am in. I am preparing a Udemy tutorial, and I would like to make a simple example. I would like to be able to double check if the method add is properly called, the arguments in properly called.
The problem is that the automocking is mocking everything. I would like to just mock the add function, as so I know what is going on.
I was able to find this solution, but I feel something is missing, when trying to transform theory in Jest.
//jest.mock("./functions"); // this happens automatically with automocking
const functions = require("./functions");
test('calculate the average', () => {
const spy = jest.spyOn(functions, 'add').mockImplementation((a, b) => console.log("I was called"));
//functions.add.mockImplementation((a, b) => a + b);
functions.average(2, 2)
//expect(functions.average(2, 2)).toBe(2);
expect(spy.mock.calls[0][1]).toBe(2);
})
Trying to implement a proposed solution, it makes sense, however, it does not work as I expected. I am unable to access the mock properties. The idea is that the information should be stored, as it does with conventional mocks, however, how can I access?
jest.mock('./functions', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('./functions');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
add: jest.fn((a, b) => a + b),
};
});
const functions = require("./functions");
test('calculate the average', () => {
const add = require("./functions").add;
functions.average(2, 2);
expect(add.mock.calls[0][1]).toBe(2);
})
tried also:
test('calculate the average', () => {
const add = require("./functions").add;
expect(functions.average(2, 2)).toBe(2);
})
This showed me that the mock is "local", even after mocking, average is calling the normal method, in the case of spy, it calls the mocked one. It seems the only solution is spy aftermath.
P.S. I changed the mocked function in order to prove which function has been called.