AngularJS $范围变量.then()单元测试

时间:2016-01-11 16:16:02

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

我试图在我的控制器中对一个函数进行单元测试但是无法使$scope变量可测试。我在我的控制器.then()中设置变量,并希望进行单元测试以确保在它到达.then块时适当设置。

我的测试控制器代码:

function submit() {
    myService.submit().then(function(responseData){
        if(!responseData.errors) {
            $scope.complete = true;
            $scope.details = [
                {
                    value: $scope.formattedCurrentDate
                },
                {
                    value: "$" + $scope.premium.toFixed(2)
                },  
            ];
        } else {
            $scope.submitError = true;
        }
    });
}

此服务呼叫的位置无关紧要。它将返回带有action: 'submitted', 'response' : 'some response'的JSON。 .then()检查responseData上是否存在错误,如果不存在则应设置一些细节。这些$ scope.details是我在下面的单元测试中尝试测试的内容:

it('should handle submit details', function () {
    var result;
    var premium = 123.45;
    var formattedCurrentDate = "2016-01-04";
    var promise = myService.submit();
    mockResponse = {
        action: 'submitted',
        response: 'some response'
    };
    var mockDetails = [
        {
            value: formattedCurrentDate
        },
        {
            value: "$"+ premium.toFixed(2)
        }   
    ];

    //Resolve the promise and store results
    promise.then(function(res) {
        result = res;
    });
    //Apply scope changes
    $scope.$apply();
    expect(mockDetails).toEqual(submitController.details);
}); 

我收到$ scope.details未定义的错误。我不确定如何让测试识别出控制器内这个$ scope数据的变化。

在我的单元测试中的每个和其他功能之前:

function mockPromise() {
    return {
        then: function(callback) {
            if (callback) {
                callback(mockResponse);
            }
        }
    }
}

beforeEach(function() {
    mockResponse = {};
    module('myApp');

    module(function($provide) {
        $provide.service('myService', function() {
            this.submit = jasmine.createSpy('submit').and.callFake(mockPromise);
        });
    });

    inject(function($injector) {
        $q = $injector.get('$q');
        $controller = $injector.get('$controller');
        $scope = $injector.get('$rootScope');
        myService = $injector.get('myService');

        submitController = $controller('myController', { $scope: $scope, $q : $q, myService: myService});
    });
});

如何在单元测试中解析promise,以便我可以$ scope。$ digest()并查看$ scope变量?

1 个答案:

答案 0 :(得分:0)

你应该看看如何用茉莉花来测试承诺 http://ng-learn.org/2014/08/Testing_Promises_with_Jasmine_Provide_Spy/

使用callFake会尝试模拟

spyOn(myService, 'submit').and.callFake(function() {
  return {
    then: function(callback) { return callback(yourMock); }
  };
});