首页 > 解决方案 > 如何测试 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

标签: javascripttypescriptjestjsstenciljs

解决方案


除了使用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'));
    }
  })

推荐阅读