【问题标题】:How to use afterEach with Mocha async unit tests?如何在 Mocha 异步单元测试中使用 afterEach?
【发布时间】:2019-02-08 16:14:14
【问题描述】:

在下面的代码中,afterEach() 被调用之前测试中的承诺已经被解决并且done() 被调用。我希望它在使用done() 完成测试后运行。这样做的正确方法是什么?

describe ("Some test", ()=>{
    afterEach(()=>{
        console.log("Done")
    })

    it("Does something", done=>{
        new Promise (resolve=>{
            let result = doSomething();
            assert.isOK(result);
            done();
        })
    })
})

【问题讨论】:

    标签: javascript unit-testing asynchronous mocha.js


    【解决方案1】:

    这不是你在 Mocha 中使用 Promises 的方式。

    Mocha 仅通过返回 Promise(不需要 done())或使用 async 函数作为测试(隐式返回 Promise)来支持异步测试,如下所示:

    describe ("Some test", ()=>{
        afterEach(()=>{
            console.log("Done")
        })
    
        it("Does something", async () => {
            const result = await someAsyncFunction();
            assert.isOK(result);
            // no need to return from this one, async functions always return a Promise.
        })
    })
    

    describe ("Some test", ()=>{
        afterEach(()=>{
            console.log("Done")
        })
    
        it("Does something", done=>{
            // note the return
            return new Promise (resolve=>{
              doSomethingWithCallback(result => {
                assert.isOK(result);
                resolve(result);
              });
            })
        })
    })
    

    请注意,在非低级代码中使用 new Promise() 构造函数被视为反模式。有关详细信息,请参阅此问题:What is the explicit promise construction antipattern and how do I avoid it?

    【讨论】:

      【解决方案2】:

      我猜下面(在整个测试运行过程中运行一个承诺)可以满足我的要求,但肯定有更好的方法......?

      let testPromiseChain = Promise.resolve();
      
      describe("Some test", () => {
          afterEach(() => {
              testPromiseChain
              .then(x=>{
                  console.log("Done")
              })
      
          })
      
          it("Does something", done => {
              testPromiseChain = testPromiseChain
                  .then(() => {
                      new Promise(resolve => {
                          let result = doSomething();
                          assert.isOK(result);
                          done();
                      })
      
                  })
      
          })
      })
      

      【讨论】:

        猜你喜欢
        • 2016-02-21
        • 2018-08-15
        • 1970-01-01
        • 2020-02-28
        • 1970-01-01
        • 2014-02-06
        • 1970-01-01
        • 2012-09-29
        • 2014-10-12
        相关资源
        最近更新 更多