我正试图像下面这样简单地调用Mocha函数
this.logSomething = function() {
console.log('======== outside it ========')
it('something inside it', function logSomething(done){
console.log('+++++++ something inside it ++++++++')
done()
})
}
来自另一个js文件。
使用mocha.run(logSomething())
======== outside it ========
出现但
+++++++ something inside it ++++++++
丢失。
我尝试使用'describe',但结果相同。有什么解决方案而不是绕过?
仅供参考,我知道可以通过将其作为Mocha测试导入并使用Mocha CLI来运行,但是我想使用此方法从我的测试套件中重新运行失败的函数,因此它可能为零或许多具有不同功能的函数的名称,这不是导入一定数量的Mocha测试的简单方法。
我还尝试了Mocha的现有重试,由于它与我们的测试不匹配,因此我没有使用它。
答案 0 :(得分:1)
导出您的logSomething
函数,将其导入另一个文件并执行它确实可以给我您所期望的行为:
lib.js
module.exports.logSomething = function() {
console.log('======== outside it ========')
it('something inside it', function logSomething(done){
console.log('+++++++ something inside it ++++++++')
done()
})
}
test.js
const {logSomething} = require('./lib');
logSomething();
logSomething();
输出
$ mocha test.js
======== outside it ========
======== outside it ========
+++++++ something inside it ++++++++
✓ something inside it
+++++++ something inside it ++++++++
✓ something inside it
2 passing (4ms)
因此,这是一个更复杂的示例:有一个test.js
,它从两个单独的文件中导入两个类。每个类都有两种方法,依次使用it()
运行mocha测试用例。
test.js
const {TestSet1} = require('./lib1');
const {TestSet2} = require('./lib2');
new TestSet1().runTest1();
new TestSet1().runTest2();
new TestSet2().runTest1();
new TestSet2().runTest2();
lib1.js
class TestSet1 {
runTest1() {
it('should run TestSet1.Test1.It1', () => {
console.log('This is output from TestSet1.Test1.It1');
});
it('should run TestSet1.Test1.It2', () => {
console.log('This is output from TestSet1.Test1.It2');
});
}
runTest2() {
it('should run TestSet1.Test2.It1', () => {
console.log('This is output from TestSet1.Test2.It1');
});
it('should run TestSet1.Test2.It2', () => {
console.log('This is output from TestSet1.Test2.It2');
});
}
}
module.exports = {TestSet1};
lib2.js
class TestSet2 {
runTest1() {
it('should run TestSet2.Test1.It1', () => {
console.log('This is output from TestSet2.Test1.It1');
});
it('should run TestSet2.Test1.It2', () => {
console.log('This is output from TestSet2.Test1.It2');
});
}
runTest2() {
it('should run TestSet2.Test2.It1', () => {
console.log('This is output from TestSet2.Test2.It1');
});
it('should run TestSet2.Test2.It2', () => {
console.log('This is output from TestSet2.Test2.It2');
});
}
}
module.exports = {TestSet2};
输出
$ mocha test.js
This is output from TestSet1.Test1.It1
✓ should run TestSet1.Test1.It1
This is output from TestSet1.Test1.It2
✓ should run TestSet1.Test1.It2
This is output from TestSet1.Test2.It1
✓ should run TestSet1.Test2.It1
This is output from TestSet1.Test2.It2
✓ should run TestSet1.Test2.It2
This is output from TestSet2.Test1.It1
✓ should run TestSet2.Test1.It1
This is output from TestSet2.Test1.It2
✓ should run TestSet2.Test1.It2
This is output from TestSet2.Test2.It1
✓ should run TestSet2.Test2.It1
This is output from TestSet2.Test2.It2
✓ should run TestSet2.Test2.It2
8 passing (9ms)