【发布时间】:2015-11-28 18:18:51
【问题描述】:
我正在寻找一种在整个 mocha 测试之前运行异步代码的方法。
这是一个测试示例,它使用参数和期望数组,并循环遍历该数组中的所有项以生成函数断言。
var assert = require('assert')
/* global describe, it*/
var fn = function (value) {
return value + ' ' + 'pancake'
}
var tests = [
{
'arg': 'kitty',
'expect': 'kitty pancake'
},
{
'arg': 'doggy',
'expect': 'doggy pancake'
},
]
describe('example', function () {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
现在,我的问题是,如果测试值来自承诺,这将如何工作,如下所示:
var assert = require('assert')
var Promise = require('bluebird')
/* global describe, it*/
var fn = function (value) {
return value + ' ' + 'pancake'
}
function getTests () {
return Promise.resolve('kitty pancake')
.delay(500)
.then(function (value) {
return [
{
'arg': 'kitty',
'expect': value
},
{
'arg': 'doggy',
'expect': 'doggy pancake'
}
]
})
}
getTests().then(function (tests) {
describe('example', function () {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
})
也试过了:
describe('example', function () {
getTests().then(function (tests) {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
})
但是在这个示例中,没有任何测试运行,因为 mocha 无法识别 describe 语句,因为它在 promise 中。
before / beforeEach 无论如何都不会帮助以格式进行测试,除非这是一个 beforeTest 钩子,它将为 mocha 提供需要在之前运行的异步操作的知识整个测试。
【问题讨论】:
标签: javascript node.js asynchronous promise mocha.js