Non riesco a far funzionare correttamente il mio test dell'unità. Ho un array $ scope che inizia vuoto, ma dovrebbe essere riempito con un $ http.get(). In ambiente reale, non ci sarebbe circa 15 o giù di lì gli oggetti nella matrice, ma per il mio test di unità Ho appena afferrato 2. Per il test di unità, ho:
expect($scope.stuff.length).toBe(2);
Ma l'errore di Jasmine è: Previsto 0 2. di essere
ecco la mia 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);
});
};
ei miei 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();
});
Ora, ovviamente, ho cambiato i nomi delle variabili e questo dato che è per lavoro, ma spero che questo sia abbastanza informazioni per permettere a chiunque di aiutarmi. Posso fornire di più se necessario. Ricevo anche un secondo errore durante la decompressione della riga .flush(), ma ci arriverò un po 'più tardi.
Qualsiasi aiuto è molto apprezzato e grazie in anticipo!
MODIFICA:
Finalmente ha funzionato! Ecco il mio codice finale:
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: Mi sono imbattuto in un altro problema, che a mio avviso potrebbe essere stata la causa principale di questo. Vedi Unit test failing when function called on startup
puoi provare a mettere ti aspetti * dopo * $ httpBackend.flush()? – meriadec
È necessario svuotarlo prima di prevedere le modifiche. – PSL