javascript - 是否可以异步定义 mocha 测试?
问题描述
正如 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();
});
});
推荐阅读
- c# - 使用 kendoUI 将表单值发布到 DB
- excel - 如何使工作表 1 的 A 列中的项目出现在 MS Excel 的同一工作簿中的工作表 2 的 A 列中
- python - Backtrader:订单创建,我希望订单立即执行(而不是后天),怎么做?
- asp.net-mvc - 如何防止缓存 Asp.NET PWA 防伪令牌?
- python - 如何使用从 Python 中的 pickle 文件加载的模型部署机器学习模型?
- php - 提交表单而不选择任何文件时,VichUploaderBundle 错误“类型为“文件”的预期参数,给出“NULL””
- wordpress - 删除所有挂起的计划 cron 作业
- amcharts - 使用滚动条时 LineSeries 中的行消失
- c++ - c ++:堆栈上的数据而不对其进行初始化
- oracle - 比较同一张表中的2组数据-oracle