jest.toThrow 无法捕获异常?
jest.toThrow unable to catch exception?
我有一个简单的功能如下
function foo({ platform }) {
if (platform === 'all') {
throw new Error('Platform value can only be android or ios');
}
return `${platform}`;
}
然后我写了单元测试如下
it('should return correct result with platform', () => {
expect(foo({ platform: 'ios' })).toBe('ios');
expect(foo({ platform: 'android' })).toBe('android');
expect(foo({platform: 'all'})).toThrow(new Error('Platform value can only be android or ios'));
});
由于最后一个测试用例没有任何有用信息,测试实际上失败了
FAIL src/utils/__test__/foo.test.ts
● foo() › should return correct result with platform
Platform value can only be android or ios
16 | }) {
17 | if (platform === 'all') {
> 18 | throw new Error('Platform value can only be android or ios');
| ^
19 | }
20 |
21 | return `${platform}`;
at xx (src/utils/foo.ts:18:11)
我也尝试用 try catch 块包裹整个 expect
但测试也没有通过
toThrow
仅在 expect
传递一个 no-arg 函数时有效,该函数可被调用以引发异常。
/* this is the only test that needs this */
expect(() => foo({platform: 'all'})).toThrow();
这是因为 JavaScript 不支持 auto-deferring 函数参数,因此 expect
无法“暂停”其参数的计算。所以 API 必须是“给我(Jest)一个函数来调用,当我准备好处理该函数可能做的事情时我会调用它”。
我有一个简单的功能如下
function foo({ platform }) {
if (platform === 'all') {
throw new Error('Platform value can only be android or ios');
}
return `${platform}`;
}
然后我写了单元测试如下
it('should return correct result with platform', () => {
expect(foo({ platform: 'ios' })).toBe('ios');
expect(foo({ platform: 'android' })).toBe('android');
expect(foo({platform: 'all'})).toThrow(new Error('Platform value can only be android or ios'));
});
由于最后一个测试用例没有任何有用信息,测试实际上失败了
FAIL src/utils/__test__/foo.test.ts
● foo() › should return correct result with platform
Platform value can only be android or ios
16 | }) {
17 | if (platform === 'all') {
> 18 | throw new Error('Platform value can only be android or ios');
| ^
19 | }
20 |
21 | return `${platform}`;
at xx (src/utils/foo.ts:18:11)
我也尝试用 try catch 块包裹整个 expect
但测试也没有通过
toThrow
仅在 expect
传递一个 no-arg 函数时有效,该函数可被调用以引发异常。
/* this is the only test that needs this */
expect(() => foo({platform: 'all'})).toThrow();
这是因为 JavaScript 不支持 auto-deferring 函数参数,因此 expect
无法“暂停”其参数的计算。所以 API 必须是“给我(Jest)一个函数来调用,当我准备好处理该函数可能做的事情时我会调用它”。