如何测试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引发的错误

解决方法

更改道具后,您必须使用异步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'));
})
,

除了使用toThrow,我们还可以通过try catch块实现类似的结果,如下所示。

模板还提供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'));
    }
  })