Jestjs 当某个值在每个钩子之前都不正确时,我如何跳过测试用例?

Jestjs 当某个值在每个钩子之前都不正确时,我如何跳过测试用例?,jestjs,Jestjs,我使用jest.js编写测试套件。以下是示例: description('testsuites',()=>{ 让用户; beforeach(异步()=>{ user=await userSerivce.getUserById('1'); 如果(!用户){ console.info('未找到用户。跳过所有测试用例'); //中断; } }); 如果(用户){ 它('t-1',()=>{ /**/ }); 它('t-2',()=>{ /**/ }); } }); 我想跳过所有测试用例,并在找不到用

我使用
jest.js
编写测试套件。以下是示例:

description('testsuites',()=>{
让用户;
beforeach(异步()=>{
user=await userSerivce.getUserById('1');
如果(!用户){
console.info('未找到用户。跳过所有测试用例');
//中断;
}
});
如果(用户){
它('t-1',()=>{
/**/
});
它('t-2',()=>{
/**/
});
}
});
我想跳过所有测试用例,并在找不到用户时将消息记录到stdout

但是得到:

 FAIL  src/condition-skip-all-test-cases/index.spec.ts
  ● Test suite failed to run

    Your test suite must contain at least one test.

      at node_modules/jest/node_modules/jest-cli/build/TestScheduler.js:256:22

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.455s
Ran all test suites matching /src\/condition-skip-all-test-cases/i.
npm ERR! Test failed.  See above for more details.
我怎样才能做到这一点?谢谢

我发现了一个与我的问题类似的问题

以下是我的解决方案:

索引规范ts

const userService={
异步getUserById(id:string):承诺{
返回null;
}
};
导出常量itif=(名称:字符串,条件:()=>boolean | Promise,cb)=>{
它(名称,异步完成=>{
if(等待条件()){
cb(完成);
}否则{
warn(`[跳过]:${name}`);
完成();
}
});
};
描述('condition-skip-all-test-cases测试套件',()=>{
异步函数isUserExists(){
const user=await userService.getUserById('1');
返回用户?真:假;
}
让getUserByIdSpy;
异步函数conditionWithMock(){
getUserByIdSpy=jest.spyOn(userService,'getUserById').mockResolvedValueOnce({userId:1});
返回isUserExists();
}
itif('如果id未找到用户,则应跳过测试',isUserExists,done=>{
expect(‘运行测试’)。toBe(‘运行测试’);
完成();
});
itif('如果用户通过id找到,则应运行测试',conditionWithMock,done=>{
log('应该运行此测试');
期望.断言(3);
expect(‘运行测试’)。toBe(‘运行测试’);
expect(jest.isMockFunction(userService.getUserById)).toBeTruthy();
getUserByIdSpy.mockRestore();
expect(jest.isMockFunction(userService.getUserById)).toBeFalsy();
完成();
});
});
单元测试结果:

通过src/条件跳过所有测试用例/index.spec.ts(15.336s)
条件跳过所有测试用例测试套件
✓ 如果id(38ms)未找到用户,则应跳过测试
✓ 如果通过id找到用户,则应运行测试(11ms)
console.warn src/condition跳过所有测试用例/index.spec.ts:14
[已跳过]:如果未通过id找到用户,则应跳过测试
console.log src/condition跳过所有测试用例/index.spec.ts:38
应该运行此测试
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个