如何构造异步功能的测试? [英] How do I structure tests for asynchronous functions?
问题描述
我习惯于使用像这样的标准NodeJs assert 库编写Mocha测试:
I'm accustomed to writing Mocha tests using the standard NodeJs assert library like this:
describe('Some module', () => {
var result = someCall();
it('Should <something>', () => {
assert.ok(...);
});
})
但是现在我的电话返回了一个承诺...所以我要写:
but now my call returns a promise... so I want to write:
describe('Some module', async () => {
var result = await someCall();
it('Should <something>', () => {
assert.ok(...);
});
})
但是它不起作用.我的测试根本没有运行.奇怪的是,
but it doesn't work. My tests don't run at all. Curiously,
describe('Some module', async () => {
it('Should <something>', () => {
var result = await someCall();
assert.ok(...);
});
})
工作正常,但问题是我想打一个电话并对它进行很多测试,所以我想在it()调用之外打这个电话
works fine but the problem is that I want to make a single call and run many tests against it, so I want to make the call outside the it() calls
我如何使其工作?
和请不推荐柴.我想使用标准的断言库
and please don't recommend Chai. I want to use the standard assert library
推荐答案
before
接受async
函数,因此您可以在测试运行之前获取result
并将其用于测试中,如下所示:
before
accepts an async
function so you can get the result
before your tests run and use it in your tests like this:
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!
});
});
这篇关于如何构造异步功能的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!