【问题标题】:Different arguments/return values for sinon expectationsinon期望的不同参数/返回值
【发布时间】:2015-06-01 14:14:05
【问题描述】:

我正在为我的模块编写单元测试,并使用 SinonJS 来验证对其他模块的函数调用的一些期望。首先,我为另一个模块注册了一个 mock:

var otherModule = {
    getConfig : function () {}
};

mockery.registerMock("otherModule", otherModule);

稍后,我运行了一些测试并(成功)验证了一些预期,例如:

var otherModuleMock = sinon.mock(otherModule);
otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

// run test

otherModuleMock.verify(); // <- succeeds

但是,当模块使用不同的参数两次调用 getConfig 函数时,我遇到了一个问题:

otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("B")
    .returns(configValuesForB);

根据我对文档的理解,这应该可行。但是,这会导致以下错误:

ExpectationError: Unexpected call: getConfig(A)
    Expectation met: getConfig(A[, ...]) once
    Expectation met: getConfig(B[, ...]) once

我尝试将 once() 替换为 atLeast(1) 或将其完全删除。我还尝试捕获otherModuleMock.expect("getConfig") 返回的期望值,并在其上应用withArgsreturns。两者都无济于事。

很确定我正在以一种不应该的方式使用mock(),但我应该如何从这里开始?

【问题讨论】:

    标签: node.js mocking mocha.js sinon


    【解决方案1】:

    结果我测试的模块实际上调用了getConfig 3 次:一次是A,一次是B,然后是A

    显然,Sinon 会跟踪所有期望/调用的顺序,这就是使用 atLeast(1) 而不是 once() 时测试甚至失败的原因。我现在看是有道理的,但这些案例并没有真正广泛地记录在 Sinon 文档中(为我自己辩护)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多