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/

相关文章:

python - 每秒重新启动一次永久运行 Python 脚本(Node.JS 模块)

mysql - Node js数组值访问问题

typescript - 在 typescript 中打字

javascript - typescript - "... is not a function or its return value is not iterable"

javascript - 如何使用 Angularjs 解析哈希后的 URL 参数?

javascript - 如何使用纯 Javascript 过滤非常大的 Bootstrap 表

node.js - Passport JWT 身份验证提取 token

javascript - 如何修复 '' http ://localhost:300 0' has been blocked by CORS policy: No ' Access-Control-Allow-Origin' header is present on the requested resource.'

javascript - 无法将属性设置为对象

javascript - 使文本在移动设备上可见,在桌面设备上不可见