I cannot get my unit test to work correctly. I have an $ scope array that starts empty but needs to be populated with $ http.get (). In a real environment, there will be about 15 or so objects in the array, but for my unit test I just grabbed 2. For unit test, I have:
expect($scope.stuff.length).toBe(2);
But jasmine's mistake: It is expected that 0 will be 2.
here is my 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); }); };
and my 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(); } );
Now, obviously, I have changed the names of the variables, etc., since this is for work, but I hope there is enough information for someone who could help me. If necessary, I can provide more. I also get a second error when uncommenting the .flush () line, but I will get to it a bit.
Any help is greatly appreciated and thanks in advance!
EDIT:
It finally works! Here is my last code:
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); } );
EDIT 2: I ran into another problem that I think could be the main reason for this. See Unit test crash when calling function at startup