【问题标题】:Not success trying to test my catch block inside of then尝试在那时测试我的 catch 块没有成功
【发布时间】:2019-08-29 22:19:30
【问题描述】:

我是单元测试代码的新手,迷路了!我正在尝试为以下函数引发错误以覆盖 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:');
    });
});

请帮帮我

【问题讨论】:

  • getQueries 是做什么的?如果它依赖于您可以模拟的其他类或资源,只需让模拟拒绝或抛出错误。
  • getQueries 返回一个 JSON.. 但如何做到这一点@p.s.w.g
  • 如果它只是返回 Json,我认为不需要 catch 块。大概它做的更多(例如,它调用一些其他方法或 API 或依赖于应用程序的其他部分来生成 Json)。您必须以某种方式模拟该过程,这将取决于您的模拟框架,也可能取决于您的测试框架。如果您还没有选择一个模拟框架,您可能需要先研究一下。我个人使用 nock 来模拟 REST API,但我知道 Jest 有自己的 mock functionality
  • 没关系,我要留着!我只是不知道如何强制 getQueries 返回错误@p.s.w.g
  • 更改了描述,现在检查是否有意义我需要什么@p.s.w.g

标签: javascript node.js typescript unit-testing


【解决方案1】:

您需要在 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:');
});

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 1970-01-01
    • 2019-03-07
    • 2017-12-13
    • 2015-10-04
    • 2016-03-16
    • 2010-12-25
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多