美文网首页Nodejs
异步代码测试

异步代码测试

作者: jinsihou19 | 来源:发表于2018-10-03 11:49 被阅读10次

    使用 Mocha 在测试异步函数的时候非常简单,只需要在回调结束的时候手动调用一下回调函数即可。向 it() 中添加一个回调函数(通常命名为 done() ),Mocha 就会知道应该等待函数调用之后完成测试。

    describe('#product', () => {
        it('should be array', (done) => {
            product.get((products) => {
                products.should.be.a.Array();
                done();
            });
        });
    });
    

    使用 PROMISE

    现在越来越多的 node 使用 Promise 来编写,Promise 的测试也是非常有必要的。
    写 Promise 的时候,直接返回一个 Promise 来代替上面的 done() 回调函数。

    describe('#feature', () => {
        it('should be array', () => feature.get().then((data) => {
            data.should.be.a.Array();
        }));
    });
    

    注意:
    在 Mocha v3.0.0 或者更新的版本中,如果既返回 Promise,又调用 done(),会抛出异常,两者只能选其一不能同时使用。在老版本中,两者同时使用时,done() 默认被忽略。

    使用 ASYNC / AWAIT

    如果运行环境支持 async / await 的时候(需 Node 版本高于或等于 v7.6.0),上面的例子可以这样书写:

    describe('product.getFeature', () => {
        it('should be array', async () => {
            const features = await product.getFeature();
            features.should.be.a.Array();
        });
    });
    

    这样一来,语义更加清晰了。

    相关文章

      网友评论

        本文标题:异步代码测试

        本文链接:https://www.haomeiwen.com/subject/czuzoftx.html