How to unit test Promise catch using Jasmine

2019-08-22 10:04发布

问题:

I have a very simple function load() that I'm trying to unit test with Jasmine. this.service.loadObject() returns a Promise.

How can I test that this.logService.error will be called if the Promise is rejected ?

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

回答1:

Something like this should work:

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();
    });
});

I'm doing setTimeout here because the promise rejects asynchronously. But Angular has cleaner ways of doing this if you need.

Edit: I haven't tested this, but based on the links below, using fakeAsync in conjunction with either tick or flushMicroTasks should work:

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");
}));