You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Meteor项目中使用Jest的mockReturnValueOnce未生效是什么原因?

问题根因

你每次调用Users.find()时,mockImplementation的回调函数都会执行一次,每次都会生成一个全新的fetch mock函数实例。也就是说你三次调用Users.find().fetch()用的是三个完全独立的fetch mock,每个mock都是第一次被调用,所以永远返回第一个预设值mock1。

解决方案

把fetch的mock实例提到find的mock逻辑外部,保证每次调用Users.find()返回的都是同一个fetch mock实例即可。

修正后的代码示例:

import { describe, test } from "@jest/globals";
import { Users } from "../../../collections"; // a Mongo collection

describe("#Users test suite", () => {
  const mock1 = {
    userId: "111aaa",
    email: "user1@test.com",
  };

  const mock2 = {
    userId: "222bbb",
    email: "user1@test.com",
  };

  const mock3 = {
    userId: "333ccc",
    email: "user1@test.com",
  };

  test("Fetch test", () => {
    // 提前定义好可复用的fetch mock实例
    const fetchMock = jest
      .fn()
      .mockReturnValueOnce(mock1)
      .mockReturnValueOnce(mock2)
      .mockReturnValueOnce(mock3);
    // 每次find调用都返回同一个fetch实例
    Users.find.mockImplementation(() => ({
      fetch: fetchMock
    }));

    console.log(Users.find().fetch()); // 输出mock1
    console.log(Users.find().fetch()); // 输出mock2
    console.log(Users.find().fetch()); // 输出mock3
  });
});

内容的提问来源于stack exchange,提问作者Marcus M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:54:06