Spys vs Mocks
Course: Testing in the MERN Stack - chapter 11
While mocks let you mock the functionality of a function call, spies let you spy on function calls.
Right now, we’ve mocked out the database call. Which means even if I pass in wrong inputs to the prismaClient.user.create function, tests would still pass
Problem
Section titled “Problem”Try flipping the a and b inputs
const response = await prismaClient.sum.create({ data: { a: parsedResponse.data.b, b: parsedResponse.data.a, result: answer }})Try running the tests, they would still work
npm run testThis means our tests are flaky. They succeed even when the code is incorrect.
Solution
Section titled “Solution”Let’s put a spy on the prismaClient.sum.create function which ensures that the db call inputs are correct
Change the first test to be
it("should return the sum of two numbers", async () => { prismaClient.sum.create.mockResolvedValue({ id: 1, a: 1, b: 1, result: 3 });
vi.spyOn(prismaClient.sum, "create");
const res = await request(app).post("/sum").send({ a: 1, b: 2 });
expect(prismaClient.sum.create).toHaveBeenCalledWith({ data: { a: 1, b: 2, result: 3 } })
expect(res.statusCode).toBe(200); expect(res.body.answer).toBe(3); });Notice that the tests begin to fail

Revert the application logic
Section titled “Revert the application logic”Make the application logic right again
const response = await prismaClient.sum.create({ data: { a: parsedResponse.data.a, b: parsedResponse.data.b, result: answer }})