javascript - 如何测试 toThrow 异常?
问题描述
在我的模板组件中,我@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
?
解决方案
除了使用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'));
}
})
推荐阅读
- javascript - 我可以在不使用 webpack 丑化的情况下缩小吗
- php - 如果belongTo 关系返回null,则返回默认值
- php - PHP回声不返回正确地
- python - 更改 ndarray 的 dtype 以使形状也发生变化
- dialogflow-es - 将自定义数据发送到对话流
- python - 从 .cache/wal/colors.css 导入后 CSS pywal 函数返回空白
- terminal - 如何使用 goorm 终端创建文件
- sql - 存储过程返回默认值?
- angular - Angular Mat 选择 CompareWith ID 号,并发出整个对象
- java - 如何对依赖于 Maven 本地存储库的 Java 应用程序进行 Docker 化?