javascript - 如何测试 toThrow 异常?
在我的 Stencil 组件中,我正在使用 @Watch 来执行如下验证
@Watch('name')
validateName(newValue: string) {
const isBlank = typeof newValue !== 'string' || newValue === '';
console.log('AYE!', isBlank);
if (isBlank) { throw new Error('name: required') };
}
现在我想开玩笑地测试这个
it('throws error when name is not supplied', async () => {
const { root } = await newSpecPage({ components: [MyComponent], html: '<my-component></my-component>' });
expect(() => {
root.name = '';
}).toThrow(new Error('name: required'))
})
我得到的结果如下
expect(received).toThrow(expected)
Expected message: "name: required"
Received function did not throw
47 | expect(() => {
48 | root.name = '';
> 49 | }).toThrow(new Error('name: required'))
| ^
50 | })
51 | });
52 |
console.log
AYE! true
at MyComponent.validateName (src/xxx/my-component.tsx:31:13)
at Array.map (<anonymous>)
我想知道我应该如何捕获 validateName 抛出的错误?
答案#1
我们可以不使用 toThrow,而是通过如下的 try catch 块来实现类似的结果。
Stencil 还提供了 waitForChanges 方法,它允许我们修改属性的值并等待其生效
it('throws error when name is not supplied', async () => {
try {
const { root, waitForChanges } = await newSpecPage({ components: [MyComponent], html: `<my-component name="xxx"></my-component>` });
root.name = '';
await waitForChanges()
} catch (e) {
expect(e).toStrictEqual(Error('name: required'));
}
})
答案#2
在更改了 prop 后,你必须使用异步的 waitForChanges()。你可以通过调用它然后使用 rejects.toEqual(...) 来检查它是否会抛出。此外,你必须返回 expect(...) 语句,否则你的测试将在异步代码完成之前就通过(并且你会在控制台中看到 UnhandledPromiseRejectionWarning)。
it('throws error when name is not supplied', async () => {
const { root, waitForChanges } = await newSpecPage({
components: [MyComponent],
html: '<my-component></my-component>'
});
root.name = '';
return expect(waitForChanges()).rejects.toEqual(new Error('name: required'));
})
