如何使用 Jasmine 对 Promise catch 进行单元测试

Luk*_*uke 2 unit-testing promise jasmine angular angular-test

我有一个非常简单的函数 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));
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*ica 5

像这样的东西应该有效:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

setTimeout在这里这样做是因为承诺异步拒绝。但如果你需要的话,Angular 有更简洁的方法来做到这一点。

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

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");
}));
Run Code Online (Sandbox Code Playgroud)