How to unit test Promise catch using Jasmine

旧街凉风 提交于 2020-01-06 14:00:33

问题


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


来源:https://stackoverflow.com/questions/53347082/how-to-unit-test-promise-catch-using-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!