簡體   English   中英

.then()單元測試中的AngularJS $ scope變量更改

[英]AngularJS $scope variable change in .then() unit testing

我正在嘗試對控制器中的函數進行單元測試,但無法獲取$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;
        }
    });
}

該服務呼叫的去向無關緊要。 它將返回JSON並帶有以下action: 'submitted', 'response' : 'some response' .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變量的變化?

您應該看看如何用茉莉花來測試諾言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); }
  };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM