Javascript 如何在mocha中以前从异步函数返回值,并在同一函数中使用相同的值?
编写代码时遇到的问题。我想减少测试中使用的代码量,但存在一些问题 我有测试,但他不工作:Javascript 如何在mocha中以前从异步函数返回值,并在同一函数中使用相同的值?,javascript,node.js,testing,mocha.js,Javascript,Node.js,Testing,Mocha.js,编写代码时遇到的问题。我想减少测试中使用的代码量,但存在一些问题 我有测试,但他不工作: var repeatTests = function(value){ it ('test1 use value', function(done){ console.log (value) // return undefined ... } it ('test2 use value', function(done){ console.l
var repeatTests = function(value){
it ('test1 use value', function(done){
console.log (value) // return undefined
...
}
it ('test2 use value', function(done){
console.log (value) // return undefined
...
}
...
}
describe ('test', function(){
var _value
before(function(done){
asyncFunction(function(err, value){
...
_value = value
...
done();
}
})
repeatTests(_value) // value is undefined
})
但这起到了作用:
describe ('test', function(){
var _value
before(function(done){
asyncFunction(function(err, value){
...
_value = value
...
done();
}
})
it ('test1 use value', function(done){
console.log(_value); // return _value
...
}
it ('test2 use value', function(done){
console.log(_value); // return _value
...
}
...
})
我知道为什么会这样。请告诉我,我如何实现测试的第一个版本 repeatTests函数与之前的函数同时调用,因此始终未定义。您可能需要使用
async.falter
。看起来是这样的:
var repeatTests = function(value){
it ('test1 use value', function(done){
console.log (value) // return undefined
...
}
it ('test2 use value', function(done){
console.log (value) // return undefined
...
}
...
}
describe ('test', function(){
var _value
async.waterfall([
before(function(done){
asyncFunction(function(err, value){
...
_value = value
...
done();
}
}),
async.apply(repeatTests,_value) //Apply for passing the parameter to the repeatTests function
],
function(err){
console.log('End of all');
}
})
谢谢,我编辑了这个问题。我尝试使用done()和不使用done(),但测试不起作用。尝试将
repeatTest(_值)
包装在一个描述块中考虑一下;我不相信这是可能的。repeatTests
函数与之前的函数同时调用,因此将始终未定义。它不起作用。如果异步函数中的it('it',function(done){})
,摩卡就不要使用这个it
。