javascript - 尝试在 then 中测试我的 catch block 没有成功

标签 javascript node.js typescript unit-testing

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

功能:

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:');
    });
});

请帮帮我

最佳答案

您需要在 Promise 解析之前对函数进行 stub 。 尝试:

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:');
});

关于javascript - 尝试在 then 中测试我的 catch block 没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55578973/

相关文章:

javascript - 使用 AJAX 填充 Bootstrap 模态主体

angularjs - JSON 树 MongoDB

node.js - 微软bot框架网络聊天直连隐藏 secret ——NODE JS

javascript - TypeError : promise. then is not a function

node.js - 如何将 Blob 添加到 Typescript?

typescript - 在映射操作期间创建时,字符串文字联合类型无法编译

javascript - xul 中的对接面板

javascript - 触发附加 anchor 标记的点击事件

javascript - 如何在 JavaScript 中调用函数内的函数

Angular2 向 DOM 树发出事件