首页 文章

使用Mocha测试Promise时出现错误

提问于
浏览
0

我正在使用mocha和chai来执行AngularJS服务的某些单元测试 . 该服务具有不同的功能,每个功能都返回一个承诺 .

我面临的问题是测试不是在等待断言之前要解决的promise值 . 我知道done()回调可以与mocha一起使用 . 所以,我've tried using that. But that'也给了我一个错误 . 这是代码:

describe('Service Test', function() {

    var factory;
    beforeEach(module('Test'));
    beforeEach(inject(function(_QueryService_){
            factory = _QueryService_;
        })
    );
    it('should check simpleQuery method',function(done){

        var promise = factory.query("args");
        var value;
        promise.then(function(data){
            value = data;
            assert.equal(1,2);
            done();
        }, function(error){
            assert.equal(3,4);
            done();
        });
    });
});

所以现在的问题是测试没有失败(应该如此) . 相反,它只是超时并给我一个错误:“ timeout of 2000ms exceeded. Ensure the done() callback is being called in this test

如果我不包括完成回调,则测试通过,因为它甚至不评估条件 .

有人可以建议修复吗?谢谢!

1 回答

  • 1

    我使用chai和mocha在Node.js中进行测试 . 我测试的大多数都是承诺 . 这里有一些示例代码可以帮助您入门 .

    var chai = require('chai'),
        expect = chai.expect;
    
    chai.use(require('chai-things'))
        .use(require('chai-as-promised'));
    chai.should();
    
    describe(' Testing:', function() {
        describe('#getBlah', function() {
            describe('If blah', function() {
                it('Should should blah', function() {
                    return service.getBlahAsync(foo, bar).should.eventually.have.length(0);
                });
            });
    
    describe('If blahblah', function() {
        it('Should should blahblah', function() {
            return service.getBlahAsync(foo, bar).should.eventually.all.have.property(foobarbaz);
        });
    });
    

    您还可以执行诸如增加测试的超时持续时间之类的操作 . 有关该文档的文档可以在here找到 .

相关问题