0

I am writing a test that looks like this:

import { getAllUsers } from "./users";
import { getMockReq, getMockRes } from "@jest-mock/express";
import User from "../../models/User";

jest.mock("../../models/User", () => ({
  find: jest.fn(), // I want to change the return value of this mock in each test.
}));

describe("getAllUsers", () => {
  test("makes request to database", async () => {
    const req = getMockReq();
    const { res, next, clearMockRes } = getMockRes();
    await getAllUsers(req, res, next);
    expect(User.find).toHaveBeenCalledTimes(1);
    expect(User.find).toHaveBeenCalledWith();
  });
});

Within the jest.mock statement, I am creating a mock of the imported 'User' dependency, specifically for the User.find() method. What I would like to do is set the return value of the User.find() method within each test that I write. Is this possible?

This SO question is similar, but my problem is that I can't import the 'find' method individually, it only comes packaged within the User dependency.

Jason A
  • 81
  • 6

1 Answers1

0

Well after much trial and error, here is a working solution:

import { getAllUsers } from "./users";
import { getMockReq, getMockRes } from "@jest-mock/express";
import User from "../../models/User";

const UserFindMock = jest.spyOn(User, "find");
const UserFind = jest.fn();
UserFindMock.mockImplementation(UserFind);

describe("getAllUsers", () => {
  test("makes request to database", async () => {
    UserFind.mockReturnValue(["buster"]);
    const req = getMockReq();
    const { res, next, clearMockRes } = getMockRes();
    await getAllUsers(req, res, next);
    expect(User.find).toHaveBeenCalledTimes(1);
    expect(User.find).toHaveBeenCalledWith();
    expect(res.send).toHaveBeenCalledWith(["buster"]);
  });
});

Note how I've used jest.spyOn to set a jest.fn() on the specific User find method, and I can use the UserFind variable to set the return value of the mock implementation.

Jason A
  • 81
  • 6