I am learning Jest, TDD to be more precise. I reading a book, and trying to adapt the concept to Jest. I am sure that if I keep studying, I will eventually find the answer. Should you be kind to let me know the answer, that would be great! thanks! here goes 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. Again, this is a learning exercise, most likely, it makes no sense on real applications. I am adapting a theory to Jest realm. The book says that this kind of test is called behavior testing.
Problem is: the automocking is mocking everything
I would like to do: just mock the add function, as so I know what is going on.
I do not want to: use spyOn, as a matter of fact, if we could use spyOn, I guess that would work to, just not sure we could.
Solution I was able to find using spy
I was able to find this solution, but I feel something is missing, when trying to transform theory in Jest. Any comment is welcome. thanks.
//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);
})
from Mocking just one function on a function array using Jest
No comments:
Post a Comment