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

问题描述 投票:4回答:3

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

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

但现在我的电话会回复一个承诺...所以我想写:

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()调用之外进行调用

我如何使其工作?

请不要推荐柴。我想使用标准的断言库

javascript async-await mocha assert
3个回答
3
投票

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

3
投票

尽管使用有点不同寻常,但一种方法可能是使用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);
  });
});

希望有所帮助


1
投票

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

Mocha的describe函数不是为异步工作而设计的。但是,it函数被设计为通过传递done回调异步工作(实际参数名称可以是任何诸如“完成”或“解析”或“完成”),返回承诺或传递async函数。

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.