【发布时间】:2019-03-24 02:32:23
【问题描述】:
我在想一个问题。这是一个示例:
index.ts
async function getUserById(id?: number) {
return new Promise((resolve, reject) => {
if (id) {
const user = { id };
resolve(user);
} else {
reject(new Error('user id is required'));
}
});
}
export { getUserById };
index.spec.ts:
import { getUserById } from './';
const coin = () => Math.random() > 0.5;
describe('should throw an error test suites', () => {
const testCount = 1000;
for (let i = 0; i < testCount; i++) {
it(`t-${i}`, async () => {
const id = coin() ? 1 : 0;
try {
const user = await getUserById(id);
expect(user).toEqual({ id });
} catch (error) {
expect(error.message).toBe('user id is required');
}
});
}
});
测试结果:
Test Suites: 1 passed, 1 total
Tests: 1000 passed, 1000 total
Snapshots: 0 total
Time: 2.637s
如您所见,我动态生成了很多测试用例。问题是在这种情况下测试用例总是会通过。我认为将correct 部分和exception 部分一起测试是不正确的。我说的对吗?
什么时候应该在测试用例中使用try-catch?
谢谢。
【问题讨论】:
标签: unit-testing jasmine mocha.js jestjs