【问题标题】:How to change the return value of a method within a mocked dependency in Jest?如何在 Jest 的模拟依赖项中更改方法的返回值?
【发布时间】:2022-01-14 00:41:01
【问题描述】:

我正在编写一个如下所示的测试:

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();
  });
});

在 jest.mock 语句中,我正在创建一个导入的“用户”依赖项的模拟,专门用于 User.find() 方法。我想做的是在我编写的每个测试中设置 User.find() 方法的返回值。这可能吗?

This SO question is similar,但我的问题是我无法单独导入“查找”方法,它只能打包在用户依赖项中。

【问题讨论】:

    标签: javascript jestjs mocking


    【解决方案1】:

    经过多次尝试和错误,这是一个可行的解决方案:

    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"]);
      });
    });
    

    注意我是如何使用 jest.spyOn 在特定的 User find 方法上设置 jest.fn() 的,我可以使用 UserFind 变量来设置模拟实现的返回值。

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 1970-01-01
      • 2019-02-14
      • 2021-12-01
      • 2020-10-17
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多