I'm trying to test a asynchronous query function using Jasmine 2.4. I have the next code for my Angular service:
var moduleApp = angular.module('myApp', ['ngResource']);
moduleApp.factory('UsersHandlingService', function ($resource) {
return $resource("/api/users/:userId:userEmail", {userEmail : '@user_email'}, {
'query': {method: 'GET', isArray: false},
'update': {method: 'PUT'}
});
});
I injected the UsersHandlingService service in my controller UsersController,then calls its function like this:
moduleApp.controller('UsersController', ['$scope', 'UsersHandlingService', function($scope, UsersHandlingService){
$scope.varController="testControllerVar";
$scope.getUsers = function() {
$scope.varTest1="Test1";
UsersHandlingService.query(function (data, getResponseHeaders) {
$scope.users = data.Users;
console.log(data);
$scope.varTest2="Test2";
}, function (errorHttpResponse) {
console.log(errorHttpResponse);
$scope.error=errorHttpResponse; //Error HTTP response in JSON format
});
};
}]);
Now the code that I used to test the Controller and the service look like this:
describe('UserController', function() {
beforeEach(module('myApp'));
var $scope, controller;
var myService;
var $httpBackend;
var getResponse = {
"Error": false,
"Message": "Success",
"Users": [
{"user_id": 45, "user_email": "John@mail.com"},
{"user_id": 52, "user_email": "Paul@mail.com"}
]
};
describe('testASYNC', function () {
var controller;
var scope;
var routeParams;
var mockUsersService = {
query: function(success, error) {
return success({
"success": true,
"Message": "SuccessMock",
"data": getResponse
});
}
};
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
controller = $controller('UsersController', {
$scope: scope,
UsersHandlingService: mockUsersService
});
}));
it('should be defined', function() {
expect(controller).toBeDefined();
});
it('should have a varTest1 variable inside getUsers function ', function() {
expect(scope.varTest1).toBeDefined();
expect(scope.varTest1).toEqual("Test1");
});
it('should have a varTest2 variable inside query function ', function() {
expect(scope.varTest2).toBeDefined();
expect(scope.varTest2).toEqual("Test2");
});
it('should have scope.users variable inside query function ', function() {
expect(scope.users).toEqual(getResponse.Users);
});
});
When I run the test, the first three tests passed but the last one failed and I get the following error:
Expected undefined to equal [ Object({ user_id: 45, user_email: 'John@mail.com'}),Object({ user_id: 52, user_email: 'Paul@mail.com'})]
I saw some examples that using done() function, but I don't know how exactly use it for test this asynchronous function. Can you please help me resolve this error?
Aucun commentaire:
Enregistrer un commentaire