Jasmine:关于测试承诺的范围问题

时间:2016-06-07 12:02:10

标签: javascript angularjs unit-testing jasmine karma-jasmine

我遇到了Jasmine的一些问题。我有点像新手,所以这可能不是一个聪明的问题。

我有一个用AngularJS编写的$ http.get服务:

app.service('commissionSvc', ['$http', function ($http) {
this.getCommissionList = function (token) {
    if (!token)
        throw Error('missing token')
    else {
        var config = {
            headers: {
                'Content-Type': "application/json",
                'Authorization': "Bearer" + token
            }
        };
        return $http.get(apiURL + '/commission/', config)
            .then(function (response) {
                return response.data;
            })
    }
}
}]);

我想在Jasmine中测试我是否会进入或接受:

    ....*code code code* ....
    it('should be in catch on errors', function () {
        httpBackend.expectGET(apiURL + '/commission/').respond(401, '');
        var whereAmI;

        commissionSvc.getCommissionList('token')
            .then(function(data){
               whereAmI = 'then'
            })
            .catch(function(error){
                whereAmI = 'catch'
           })

        expect(whereAmI).toEqual('catch');
        httpBackend.flush();
    });
    ....* code code code *....

问题是在然后 catch 函数内部,变量whereAmI未定义,我无法完成测试。

有没有办法将变量传递给then / catch函数? 这是对这种服务的这种行为进行单元测试的正确方法吗?

谢谢,

曼努埃尔

ANSWER

正如评论中所建议的,在我的测试中切换最后两行就足够了。因此测试看起来像:

    ....*code code code* ....
    it('should be in catch on errors', function () {
        httpBackend.expectGET(apiURL + '/commission/').respond(401, '');
        var whereAmI;

        commissionSvc.getCommissionList('token')
            .then(function(data){
               whereAmI = 'then'
            })
            .catch(function(error){
                whereAmI = 'catch'
           })
        httpBackend.flush();          
        expect(whereAmI).toEqual('catch');
      });
    ....* code code code *....

0 个答案:

没有答案
相关问题