catch进行单元测试

catch进行单元测试

本文介绍了如何使用茉莉花对Promise catch进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

类似的方法应该起作用:

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

我在这里执行setTimeout,因为Promise异步拒绝.但是Angular可以根据需要提供更干净的方法.

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

编辑:我尚未对此进行测试,但是基于下面的链接,将fakeAsynctickflushMicroTasks结合使用应该可以:

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/在带角度的fakeasync中测试异步代码/ 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");
}));

这篇关于如何使用茉莉花对Promise catch进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:15