摩卡从之前退出功能,如果条件不匹配



在下面的代码逻辑中(抱歉没有复制确切的代码(,如果在任何文件中都找不到"xyz"数据,我想退出测试。基本上想在"if"条件不对单个文件执行时退出。

private testFileNames(testFiles: string[]) {
const self = this;
describe('test', async function() {
before(async function() {
for (let testFile of testFiles) {
//read data from file
if (find xyz data in file) {
//set up test
}
// code to add listeners
}
}
////Want to exit here after for loop finishes and if xyz data is not found in any file
});

it(`test should complete without errors`, async function() {
//some code

当与async/await一起使用时,您可以在before钩子中抛出一个新错误。或者,将错误参数传递给 done(( 函数。这将退出测试,并且不会运行后续测试用例。

例如

describe('test', function () {
before(async function () {
const xyz = 'd';
const file = 'aa';
if (!file.includes(xyz)) {
throw new Error(`exit test. reason: '${xyz}' data not found`);
}
});
it('should pass 1', () => {});
it('should pass 2', () => {});
it('should pass 3', () => {});
});

测试结果显示错误发生在before挂钩中:

test
1) "before all" hook for "should pass 1"

0 passing (137ms)
1 failing
1) test
"before all" hook for "should pass 1":
Error: exit test. reason: 'd' data not found
at Context.<anonymous> (src/stackoverflow/61846578/index.test.ts:6:13)
at Generator.next (<anonymous>)
at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/61846578/index.test.ts:8:71
at new Promise (<anonymous>)
at __awaiter (src/stackoverflow/61846578/index.test.ts:4:12)
at Context.<anonymous> (src/stackoverflow/61846578/index.test.ts:13:16)

npm ERR! Test failed.  See above for more details.

最新更新