【问题标题】:How to set the return value of a function within a mocked dependency in Jest?如何在 Jest 的模拟依赖项中设置函数的返回值?
【发布时间】:2022-06-30 04:01:13
【问题描述】:

我正在尝试模拟 mongoose 模型,以便对 express 控制器进行单元测试。我已经删除了所有不相关的代码以显示我正在尝试做的事情。这是要测试的代码:

import User from "../../models/User";

const getAllUsers = async () => {
  const users = await User.find(); // I want to mock the return value of User.find()
  return users;
};

export { getAllUsers };

这是测试文件:

import { getAllUsers } from "./discord";
import User from "../../models/User";

jest.mock("../../models/User", () => ({
  find: jest.fn(),
}));

describe("getAllUsers", () => {
  test("makes read request to database", async () => {
    User.find.mockResolvedValueOnce("some result"); // Causes error. How can I mock User.find?
    const result = await getAllUsers();
    expect(User.find).toHaveBeenCalledTimes(1);
    expect(result).toBe("some result");
  });
});

在测试文件中,User.find 未被识别为模拟。我收到以下测试失败:

 FAIL  src/controllers/users/discord.test.ts
  ● Test suite failed to run

    src/controllers/users/discord.test.ts:10:15 - error TS2339: Property 'mockResolvedValueOnce' does not exist on type '{ (callback?: Callback<(Document<any, any, UserInterface> & UserInterface & { _id: ObjectId; })[]> | undefined): Query<...>; (filter: FilterQuery<...>, callback?: Callback<...> | undefined): Query<...>; (filter: FilterQuery<...>, projection?: any, options?: QueryOptions | ... 1 more ... | undefined, callback?: Callb...'.

    10     User.find.mockResolvedValueOnce("some result");
                     ~~~~~~~~~~~~~~~~~~~~~

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.193 s

如何模拟 User find 方法?

请注意,我想在我编写的每个单独测试中更改 User.find() 的模拟返回值。我还想模拟来自 User 的其他方法,例如 findById(),但为了写这篇文章,我只关注 find() 方法。

编辑:我创建了this sandbox 以方便他人帮助我。

【问题讨论】:

    标签: typescript unit-testing jestjs mocking


    【解决方案1】:

    我认为你应该使用这样的东西:

    const resultReport = repositoryPort.findById = jest.fn(() => of(mockLoan));

    mockLoan 是您想要返回的模拟。

    【讨论】:

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