代码之家  ›  专栏  ›  技术社区  ›  TLP

如何使用Aftereach和Mocha异步单元测试?

  •  1
  • TLP  · 技术社区  · 7 年前

    在下面的代码中, afterEach() 被调用 之前 测试中的承诺已得到解决, done() 被调用。我希望它在测试完成后运行 DONE() . 正确的方法是什么?

    describe ("Some test", ()=>{
        afterEach(()=>{
            console.log("Done")
        })
    
        it("Does something", done=>{
            new Promise (resolve=>{
                let result = doSomething();
                assert.isOK(result);
                done();
            })
        })
    })
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Madara's Ghost    7 年前

    这不是你在摩卡使用承诺的方式。

    Mocha只通过返回一个承诺来支持异步测试(不需要 done() )或使用 async 用作测试(隐式返回承诺),如:

    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
  •  0
  •   TLP    7 年前

    我想下面(在整个测试运行中运行一个承诺)是我想要的,但肯定有更好的方法……

    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();
                    })
    
                })
    
        })
    })