【问题标题】:mock the same function twice in the same test differently based on the argument I sent根据我发送的参数,在同一测试中以不同方式模拟同一函数两次
【发布时间】:2021-08-29 18:26:46
【问题描述】:

我有以下代码:

it('Should return error', async () => {
  const searchMetadata = {
    details: {}
  };
  sandbox.mock(resultService).expects('doesSearchExists').atLeast(1).resolves(true);
  sandbox.mock(resultService).expects('doesSearchExists').atLeast(1).withArgs("limit").resolves(false);
  sandbox.mock(analyticsService).expects('getMetadata').throws(UNABLE_TO_CALCULATE_METADATA);
  await GET(request, res, (result: any) => {
    expect(result).to.be.deep.equal(UNABLE_TO_CALCULATE_METADATA)
  });
});

如您所见,我试图根据我发送的参数两次不同地模拟相同的函数 doesSearchExists。如果发送了限制,dosSearchExists 应该返回 false,如果缺少限制,doSearchExists 应该返回 true。但是当我尝试它时,我得到了

TypeError: Attempted to wrap doesSearchExists which is already wrapped

知道如何实现上述目标吗?

【问题讨论】:

  • 您需要存储模拟并在第二次设置中重复使用它。

标签: node.js unit-testing sinon


【解决方案1】:

我创建了a runnable example 来解决您的问题。

// Employs 'mini-mocha' to emulate running in the Mocha test runner (mochajs.org)
require("@fatso83/mini-mocha").install();

const sinon = require("sinon");
const {assert} = require('@sinonjs/referee');

// The SUT
const resultService = {
    doesSearchExists(arg) {}
}

describe("SO67960235", function() {
    const sandbox = sinon.createSandbox();

    it('Should return error <-- this title is wrong', async () => {

      // setup mocks
      const mock = sandbox.mock(resultService)
      mock.expects('doesSearchExists').atLeast(1).resolves(true);
      mock.expects('doesSearchExists').atLeast(1).withArgs("limit").resolves(false);
      
      // call your external methods that exercise your mocks
      console.log(await resultService.doesSearchExists("foo")); // true
      console.log(await resultService.doesSearchExists("limit")); // false

      // verify that they were called as expected
      mock.verify();
    });
});

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2022-11-29
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多