【问题标题】:Using Sinon to test after promise resolutionPromise解决后使用Sinon进行测试
【发布时间】:2017-10-13 14:28:30
【问题描述】:

我有一些在 promise 解决后执行的代码。我正在尝试监视一个应该在承诺后解决方​​案中调用的方法,但是在调用对监视的方法的调用之前,我的测试完成执行时遇到问题。

我如何测试对storage.add 的调用实际上是在进行的?

这是测试:

"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    tested._execute();

    expect(
        storageStub.calledWith("name", true)
    ).to.be.true
}

下面是实现:

_execute: function() {
    this.updateServiceApi().then(function(){
        // tests finish before this code is executed :(
        storage.add("name", true);
    });
},

【问题讨论】:

  • 你用的是什么测试运行器?

标签: javascript promise mocking sinon spy


【解决方案1】:

这里的问题是您编写的测试好像_execute 是同步的。

由于承诺,expect 调用将在 storage.add() 调用之前执行。

具体如何处理这将取决于测试运行程序,但一般解决方法是在测试中的被调用函数中添加一个.then(),其中将包含您的expect 代码。

"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    return tested._execute()
        .then(() => {
             expect(storageStub.calledWith("name", true)).to.be.true;
        });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2019-01-17
    • 2019-05-24
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多