단위 테스트를 제대로 수행 할 수 없습니다. 비어있는 곳으로 시작하는 $ scope 배열이 있지만 $ http.get()으로 채워야합니다.
expect($scope.stuff.length).toBe(2);
그러나 재스민의 오류는 다음과 같습니다 : 실제 환경에서, 배열의 약 15 정도의 물체가있을 것입니다,하지만 내 단위 테스트를 위해 난 그냥 단위 테스트를 위해 2를 잡고, 나는이 0을 예상 2.
로하는 것은 여기 내 controller.js입니다 :
$scope.stuff = [];
$scope.getStuff = function() {
var url = site.root + 'api/stuff';
$http.get(url)
.success(function (data) {
$scope.stuff = data;
})
.error(function(error) {
console.log(error);
});
};
내 controller.spec.js 것은 :
/// <reference path="../../../scripts/angular-loader.min.js" />
/// <reference path="../../../scripts/angular.min.js" />
/// <reference path="../../../scripts/angular-mocks.js" />
/// <reference path="../../../scripts/angular-resource.js" />
/// <reference path="../../../scripts/controller.js" />
beforeEach(module('ui.router'));
beforeEach(module('ngResource'));
beforeEach(module('ngMockE2E'));
beforeEach(module('myApplication'));
var $scope;
var controller;
var httpLocalBackend;
beforeEach(inject(function ($rootScope, $controller, $injector) {
$scope = $rootScope.$new();
controller = $controller("StuffController", {
$scope: $scope
});
}));
beforeEach(inject(function ($httpBackend) {
httpLocalBackend = $httpBackend;
}));
it('should get stuff', function() {
var url = '/api/stuff';
var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }];
httpLocalBackend.expectGET(url).respond(200, httpResponse);
$scope.getStuff();
expect($scope.stuff.length).toBe(2);
//httpLocalBackend.flush();
});
자, 분명히, 변수 이름 등을 변경했는데, 이것은 작업을위한 것이기 때문에, 이것은 누군가가 나를 도울 수있는 충분한 정보 일 것입니다. 필요한 경우 더 제공 할 수 있습니다. 또한 .flush() 행의 주석 처리를 제거 할 때 두 번째 오류가 발생하지만 나중에 약간 알아 보겠습니다.
어떤 도움을 주셔서 감사 드리며 미리 감사드립니다.
편집 :
마지막으로 작동했습니다!
it('should get stuff', function() {
var url = '/api/stuff';
var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }];
httpLocalBackend.expectGET(url).respond(200, httpResponse);
$scope.getStuff();
httpLocalBackend.flush();
expect($scope.stuff.length).toBe(2);
});
편집 2 : 여기 내 마지막 코드는 내가 이것의 근본 원인되었을 수 있습니다 생각하는 또 다른 문제 다 퉜다. Unit test failing when function called on startup
* * $ httpBackend.flush() 이후에 * 당신이 기대할 수 있습니까? – meriadec
변경 사항을 예상하기 전에 플러시해야합니다. – PSL