如何构建异步函数的测试?

How do I structure tests for asynchronous functions?

我习惯于使用标准的 NodeJs assert 库编写 Mocha 测试,如下所示:

describe('Some module', () => {
   var result = someCall();
   it('Should <something>', () => {
      assert.ok(...);
   });
})

但现在我打电话 returns 一个承诺...所以我想写:

describe('Some module', async () => {
   var result = await someCall();
   it('Should <something>', () => {
      assert.ok(...);
   });
})

但它不起作用。我的测试根本没有 运行。奇怪的是,

describe('Some module', async () => {
   it('Should <something>', () => {
      var result = await someCall();
      assert.ok(...);
   });
})

工作正常,但问题是我想进行一次调用,运行 对其进行多次测试,所以我想在 it() 调用之外进行调用

如何让它发挥作用?

不推荐Chai。我想使用标准断言库

虽然在使用上有点不合常规,但一种方法可能是使用 before() hook 来实现您的要求。

before() 挂钩将提供一种在套件中的其余测试之前调用功能(即 someCall())的方法。钩子本身支持通过回调函数(即 done)执行异步功能,一旦异步功能完成就可以调用该回调函数:

before((done) => {
  asyncCall().then(() => {
    /* Signal to the framework that async call has completed */
    done(); 
  });
});

将其与现有代码集成的一种方法如下:

describe("Some module", () => {
  /* Stores result of async call for subsequent verification in tests */
  var result;

  /* User before hook to run someCall() once for this suite, and
  call done() when async call has completed */
  before((done) => {
    someCall().then((resolvedValue) => {
      result = resolvedValue;
      done();
    });
  });

  it("Should <something>", () => {

    /* result variable now has resolved value ready for verification */
    console.log(result);
  });
});

希望对您有所帮助

before 接受一个 async 函数,因此您可以在测试前获得 result 运行 并在测试中使用它,如下所示:

const assert = require('assert');

const someCall = () => Promise.resolve('hi');

describe('Some module', () => {
  let result;

  before(async () => {
    result = await someCall();
  });

  it('Should <something>', () => {
    assert.equal(result, 'hi');  // Success!
  });
});

摩卡已经支持你想做的事了。

Mocha 的 describe 函数不是为异步工作而设计的。但是,it 函数被设计为通过传递 done 回调(实际参数名称可以是 "complete" 或 "resolve" 或 "done"), 返回承诺或传递 async 函数。

这意味着您的测试 几乎 正确。您只需要这样做:

describe('Some module', () => {
   it('Should <something>', async () => {
      var result = await someCall();
      assert.ok(...);
   });
})

如果您需要 运行 对多个 it 块执行一次 someCall() 函数,您可以按照其他答案中的说明进行操作,并在 before 块中调用它.