尝试在其中测试我的catch块没有成功

时间:2019-04-08 17:44:37

标签: javascript node.js typescript unit-testing

我是单元测试代码的新手,迷路了!我正在尝试为以下函数引发错误以覆盖catch块,但没有成功,我也不知道为什么。

功能:

public initialize(): Promise<this> {
    return Promise.resolve()
      .then(() => this.getQueries())
      .catch((error: Error) => {
        this.connector.localLog.error(error, 'Failed to initialize Rest Poller Launcher:');
        throw error;
      });
  }

单元测试:

it('should getQueries return error', () => {
  launcher.initialize()
    .then(() => {
      this.getQueries = stub().throws('TypeError');
    })
    .catch((error: Error) => {
      expect(error.message).equals('Failed to initialize Rest Poller Launcher:');
    });
});

请帮助我

1 个答案:

答案 0 :(得分:4)

您需要先对函数进行存根,然后再解决Promise。 试试:

it('should getQueries return error', () => {
launcher.getQueries = stub().throws('TypeError');
launcher.initialize()
.then(() => {
// this should not happen
})
.catch((error: Error) => {
  expect(error.message).equals('Failed to initialize Rest Poller Launcher:');
});