【问题标题】:Testing promises with mocha chai and sinon用 mocha chai 和 sinon 测试 promise
【发布时间】:2015-12-01 10:04:11
【问题描述】:

我想使用mochachaisinon 测试我的承诺解析处理程序和承诺拒绝处理程序。此外,我已经设置了sinon-chai 插件和sinon-stub-promise 插件。

这是我的要求语句块:

var chai = require('chai');
var expect = chai.expect;
var sinonChai = require('sinon-chai');
chai.use(sinonChai);
var sinon = require('sinon');
var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

这是我的测试套件:

describe('Connect to github users',function(done){

    var api = require('../users'),
        onSuccess = api.onSuccess,
        onError = api.onReject; 
    console.dir(api);
    //the idea is not to test the async connection,the idea is to test 
    //async connection but to test how the results are handled.
    var resolveHandler,
        rejectHandler,
        getPromise,
        result;

    beforeEach(function(){
        resolveHandler = sinon.spy(onSuccess);
        rejectHandler = sinon.spy(onError);
        getPromise = sinon.stub().returnsPromise();
    });

    it('must obtain the result when promise is successful',function(){
        result = [...];//is an actual JSON array    
        getPromise.resolves(result);

        getPromise()
            .then(resolveHandler)
            .catch(rejectHandler);

        expect(resolveHandler).to.have.been.called();//error 
        expect(resolveHandler).to.have.returned(result);
        expect(rejectHandler).to.have.not.been.called();    
        done();
    });

    afterEach(function(){
        resolveHandler.reset();
        rejectHandler.reset();
        getPromise.restore();
    });

});

我发现自己遇到了这个错误:

 Connect to github users must obtain the result when promise is successful:
 TypeError: expect(...).to.have.been.called.toEqual is not a function
  at Context.<anonymous> (C:\Users\vamsi\Do\testing_promises\test\githubUsersSpec.js:94:46)

【问题讨论】:

  • 存根 promise 是否同步?
  • 实现是thenable,它可以与任何具有then 的东西链接在一起,包括我不想做的真正的承诺,所以我使用@ 987654332@ 和 rejects 仅测试处理程序。我在观看this video 之后尝试了这个,他在其中捕获了 jQuery ajax 成功回调的参数,
  • 是的,我只是想知道您希望处理程序在您附加它们之后立即被调用。正常的承诺会失败。

标签: javascript promise mocha.js sinon sinon-chai


【解决方案1】:

sinon-with-promise 包应该适合您正在尝试做的事情。我遇到了同样的问题(除了我不需要测试拒绝案例)并且效果很好。

【讨论】:

    【解决方案2】:

    这里这行代码是错误的:

    expect(resolveHandler).to.have.been.called();
    

    called 只是spy 上的一个属性,其值始终为boolean,可以像这样使用chai 进行简单测试:

    expect(resolveHandler.called).to.equal(true);
    

    类似地代替这一行来确认函数没有被拒绝:

    expect(rejectHandler).to.have.not.been.called();
    

    将此与called 一起用作属性:

    expect(rejectHandler.called).to.equal(false);
    

    【讨论】:

    • 代码没有错,他正在尝试使用sinon-chai,因此to.have.been.called是有效代码。
    猜你喜欢
    • 1970-01-01
    • 2016-06-11
    • 2018-04-08
    • 2016-05-26
    • 2019-02-04
    • 2023-04-11
    • 2017-09-14
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多