0
我正在使用Jasmine與angular-mocks
'httpBackend
一起編寫角度單元測試。
我已經設法正確地模擬我的後端,但我的一些測試有一個http調用的問題,其中在請求完成之後將值設置爲scope
(在then()
)。
控制器: $scope.startShift
綁定到按鈕單擊。
app.controller('ShiftStartCntl', function($scope, $rootScope, $location, Restangular, $http, shifts) {
$scope.shifts = shifts;
$scope.startShift = function (category) {
$scope.startingShift = true;
baseShifts.post({category_number: 2})
.then(function (shift) {
$scope.shift = shift;
// breaks here if run as the endpoint isn't mocked
$http.post('endpointThatIsNotMocked').then(function() {});
$location.path($scope.rootURL + '/shift/' + shift.id + '/');
$scope.startingShift = false;
});
});
測試:
// module definition and stuff
//
// [...]
//
describe('ShiftStartCntl', function() {
var scope, rootScope, httpBackend, ShiftStartCntl;
beforeEach(angular.mock.inject(function($rootScope, $controller, $httpBackend) {
scope = $rootScope.$new();
rootScope = $rootScope;
httpBackend = $httpBackend;
// mimics the controller's ng-route `resolve` dependency
shifts = getJSONFixture('leave_shifts.json');
scope.baseShifts = baseApi.all('shifts');
// used in the controller
scope.categories = getJSONFixture('leave_categories.json');
httpBackend.expectPOST('/api/shifts/', {category_number: 2})
.respond(203, {"id": 4, "user": 1,
"category_number": 2,
"sign_in": "2015-02-10T21:29:06.110Z",
"sign_out": null
});
$controller('ShiftStartCntl', {$scope: scope, shifts: []});
}));
it('should start a shift', function() {
expect(shifts.length).toEqual(2);
expect(scope.startingShift).toBe(undefined);
scope.startShift(scope.categories[1]);
rootScope.$apply();
expect(scope.shift.id).toEqual(4);
httpBackend.flush();
});
});
所產生的誤差是:
PhantomJS 1.9.8 (Mac OS X) Shifts ShiftStartCntl should start a shift FAILED
Expected undefined to equal 4.
at [...]/js/tests/unit/controllers/main.js:100
Error: Unexpected request: POST yoyoyo
這是行,其中expect(scope.shift.id).toEqual(4);
我的問題是關於意外請求錯誤應在0執行前發生。
閱讀幾個Stackoverflow的答案和各種博客帖子,我試過使用$rootScope.apply();
沒有成功。
關於如何解決這個問題的任何想法?
花了幾個小時嘗試...歡呼 – rxdazn 2015-02-11 04:23:46