How to test that an angular factory function using a promise is throwing an error in jasmine

你。 提交于 2019-12-04 17:12:31
Michael Radionov

$q does not work well with native throw, you should use $q API to re-throw or create new errors inside promise chain. Some Q/A to read about it:

The solution will be to use return $q.reject('Error in my function') instead of throw new Error('Error in my function');.

But the open question is how to test it. Basically you can make use of promise chains and add one more .catch() in test to check for error, and test is using Jasmine Async API:

it('should throw an error', function (done) {
// ----- use Jasmine async API -------^^^

    var instance = instanceFactory.createInstance(someData);
    var deferred = $q.defer();
    spyOn(someFactory, 'someMethod').and.returnValue(deferred.promise);

    // here we continue catching and check the error
    var promise = instance.myFunc(otherData);
    promise.catch(function (err) {
        expect(err).toBe('Error in my function');
        done();
    });

    deferred.reject({data: '12 - error'});
    $rootScope.$digest();
});

Here is a working sample (open script.js file in sidebar)

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