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

如何使用wait用mocha测试异步代码

  •  2
  • deathangel908  · 技术社区  · 7 年前

    如何用mocha测试异步代码?我想用多个 await

    var assert = require('assert');
    
    async function callAsync1() {
      // async stuff
    }
    
    async function callAsync2() {
      return true;
    }
    
    describe('test', function () {
      it('should resolve', async (done) => {
          await callAsync1();
          let res = await callAsync2();
          assert.equal(res, true);
          done();
          });
    });
    

      1) test
           should resolve:
         Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
          at Context.it (test.js:8:4)
    

    如果我删除done(),我会得到:

      1) test
           should resolve:
         Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/tmp/test/test.js)
    
    1 回复  |  直到 6 年前
        1
  •  55
  •   nicholaswmin    6 年前

    摩卡 supports Promises out-of-the-box ; 你只需要 return it() . 如果它解决了,那么测试就通过了,否则它就失败了。

    async functions always implicitly return a Promise

    async function getFoo() {
      return 'foo'
    }
    
    describe('#getFoo', () => {
      it('resolves with foo', () => {
        return getFoo().then(result => {
          assert.equal(result, 'foo')
        })
      })
    })
    

    你不需要 done 异步 为了你的 it .

    async/await :

    async function getFoo() {
      return 'foo'
    }
    
    describe('#getFoo', () => {
      it('returns foo', async () => {
        const result = await getFoo()
        assert.equal(result, 'foo')
      })
    })
    

    无论哪种情况, 不要 声明

    如果您使用上述任何方法,则需要删除 完成 完全脱离你的代码。经过 完成 作为一个论据 提示摩卡,你打算最终调用它。

    这个 完成

    推荐文章