我使用jest.js
编写测试套件。这是示例:
describe('test suites', () => {
let user;
beforeEach(async () => {
user = await userSerivce.getUserById('1');
if(!user) {
console.info('user not found. Skip all test cases');
// break;
}
})
if (user) {
it('t-1', () => {/**/})
it('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.
我该如何实现?谢谢。
我发现了一个与我的问题类似的问题。 https://github.com/facebook/jest/issues/3652
答案 0 :(得分:0)
这是我的解决方法:
index.spec.ts
:
const userService = {
async getUserById(id: string): Promise<object | null> {
return null;
}
};
export const itif = (name: string, condition: () => boolean | Promise<boolean>, cb) => {
it(name, async done => {
if (await condition()) {
cb(done);
} else {
console.warn(`[skipped]: ${name}`);
done();
}
});
};
describe('condition-skip-all-test-cases test suites', () => {
async function isUserExists() {
const user = await userService.getUserById('1');
return user ? true : false;
}
let getUserByIdSpy;
async function conditionWithMock() {
getUserByIdSpy = jest.spyOn(userService, 'getUserById').mockResolvedValueOnce({ userId: 1 });
return isUserExists();
}
itif('should skip the test if no user found by id', isUserExists, done => {
expect('run test').toBe('run test');
done();
});
itif('should run the test if user found by id', conditionWithMock, done => {
console.log('should run this test');
expect.assertions(3);
expect('run test').toBe('run test');
expect(jest.isMockFunction(userService.getUserById)).toBeTruthy();
getUserByIdSpy.mockRestore();
expect(jest.isMockFunction(userService.getUserById)).toBeFalsy();
done();
});
});
单元测试结果:
PASS src/condition-skip-all-test-cases/index.spec.ts (15.336s)
condition-skip-all-test-cases test suites
✓ should skip the test if no user found by id (38ms)
✓ should run the test if user found by id (11ms)
console.warn src/condition-skip-all-test-cases/index.spec.ts:14
[skipped]: should skip the test if no user found by id
console.log src/condition-skip-all-test-cases/index.spec.ts:38
should run this test
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total