Jasmine:如何期望promise处理程序不抛出异常

时间:2016-06-22 15:21:28

标签: javascript jasmine es6-promise

我有这个功能:

reload() {
    myService.queryData()
        .done(...)
        .always(() => throw "fake exception"); //just to simulate the failure
}

我想要我的测试重载功能,并确保它不会抛出异常,也不会发出promise回调。

describe("reload", function () {
    it("does not throw exception", function (done) {

        spyOn(myService, "queryData").and.callFake(() => {
            let deffered = $.deffered();
            setTimeOut(() => deffered.reject(), 0)
            return deffered.promise();
        });

        reload();
        setTimeout(() => {
           //this is evaluated after the exception has been thrown, but
           //how to check whether exception has been thrown
        }, 2);
    });
});

编辑:在某些情况下,我可能无法返回一个承诺,其中函数的返回类型已经定义,例如组件的生命周期事件:

MyComponent extends React.Component {
    componentDidMount() {
        this.load(
            galleryService.nodes().then(galleryResult => this.setState({ nodes: galleryResult.nodes }))
        );
        this.load(
            galleryService.caches().then(cachesResult => this.setState({ caches: cachesResult.caches }))
        );
    }
}

var myComponent = React.createElement(MyComponent);
TestUtils.renderIntoDocument(myComponent); //this triggers the componentDidMount event and I need to make sure it won't throw error.

2 个答案:

答案 0 :(得分:3)

reload返回它创建的承诺。在您的测试用例中,附加一个catch处理程序,它会触发测试失败:

reload().catch(err => done.fail(err));

编辑问题后更新:如果无法更改原始功能的返回值,则将相关部分分解为单独的功能。例如:

function reloadNodes() {
    return somePromise();
}

function reloadCaches() {
    return anotherPromise();
}

function reload() {
    reloadNodes();
    reloadCaches();
}

然后,您可以测试reloadNodesreloadCaches而不是reload。显然,您不需要为每个承诺创建单独的函数,而是在适当的情况下使用Promise.all之类的内容组合您的承诺。

答案 1 :(得分:0)

我相信对window.onerror进行间谍活动是可行的方法:

describe("reload", function () {
    it("does not throw an exception", function (done) {

            spyOn(window, 'onerror').and.callFake((error: any, e: any) => {
                fail(error);
            });

            spyOn(myService, "queryData").and.callFake(() => {
               let deffered = $.deffered();
               setTimeout(deffered.reject, 0);
               return deffered.promise();
           });
        });
        setTimeout(done, 2);
    });
});