是否可以异步定义摩卡测试?
Is it possible to define mocha tests asynchronously?
正如 mocha 文档中所指出的,可以动态生成测试:
var assert = require('chai').assert;
function add() {
return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
];
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});
我遇到的问题是我想根据异步函数的结果生成测试。像这样:
describe('add()', function() {
asyncFunctionThatReturnsAPromise()
.then(tests => {
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});
});
但是,执行时会产生 0 个测试用例。
是否完全不支持异步定义测试,或者是否有办法做到这一点?
我刚刚找到了操作方法。如果你用 --delay
标志执行 mocha,run()
将在全局范围内定义,你的测试套件将不会执行,直到 run()
被调用。这是一个例子:
describe('add()', function() {
asyncFunctionThatReturnsAPromise()
.then(tests => {
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
run();
});
});
正如 mocha 文档中所指出的,可以动态生成测试:
var assert = require('chai').assert;
function add() {
return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
];
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});
我遇到的问题是我想根据异步函数的结果生成测试。像这样:
describe('add()', function() {
asyncFunctionThatReturnsAPromise()
.then(tests => {
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});
});
但是,执行时会产生 0 个测试用例。
是否完全不支持异步定义测试,或者是否有办法做到这一点?
我刚刚找到了操作方法。如果你用 --delay
标志执行 mocha,run()
将在全局范围内定义,你的测试套件将不会执行,直到 run()
被调用。这是一个例子:
describe('add()', function() {
asyncFunctionThatReturnsAPromise()
.then(tests => {
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
run();
});
});