【问题标题】:How to unit test Promise catch using Jasmine如何使用 Jasmine 对 Promise 捕获进行单元测试
【发布时间】:2019-04-20 04:28:46
【问题描述】:

我有一个非常简单的函数 load(),我正在尝试使用 Jasmine 进行单元测试。 this.service.loadObject() 返回一个 Promise。

如果 Promise 被拒绝,我如何测试 this.logService.error 会被调用?

load() {
    this.service.loadObject().then(x => {
       this.variable = x;
    }).catch(ex => this.logService.error(ex));
}

【问题讨论】:

  • 在这种情况下,您可能可以使用Spy 来告诉您是否调用了某个函数。

标签: angular unit-testing promise jasmine angular-test


【解决方案1】:

这样的事情应该可以工作:

it("should catch the error", done => {
    spyOn(service, "loadObject").and.returnValue(Promise.reject("test error"));
    spyOn(logService, "error"); // Might need to mock this method too

    load();

    setTimeout(() => {
        expect(logService.error).toHaveBeenCalledWith("test error");
        done();
    });
});

我在这里做setTimeout 因为承诺异步拒绝。但是如果你需要,Angular 有更简洁的方法来做这件事。

编辑:我没有对此进行测试,但根据下面的链接,将fakeAsynctickflushMicroTasks 结合使用应该可以工作:

https://www.joshmorony.com/testing-asynchronous-code-with-fakeasync-in-angular/ https://alligator.io/angular/testing-async-fakeasync/

it("should catch the error", fakeAsync(() => {
    spyOn(service, "loadObject").and.returnValue(Promise.reject("test error"));
    spyOn(logService, "error"); // Might need to mock this method too

    load();

    // One of these
    // flushMicroTasks();
    // tick();

    expect(logService.error).toHaveBeenCalledWith("test error");
}));

【讨论】:

  • 直到我记得只有一个异步线程(事件循环)之前,我无法理解为什么这是有效的。谢谢你。有哪些更简洁的方法可以做到这一点?
猜你喜欢
  • 2021-01-28
  • 2017-02-28
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多