我正在尝试使用Jasmine 2.4测试异步查询功能。我有我的Angular服务的下一个代码:
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'}
});
});
我在我的控制器UsersController中注入了UsersHandlingService服务,然后调用它的函数:
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
});
};
}]);
现在我用来测试Controller和服务的代码如下所示:
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);
});
});
当我运行测试时,前三个测试通过但最后一个测试失败,我收到以下错误:
Expected undefined to equal [ Object({ user_id: 45, user_email: 'John@mail.com'}),Object({ user_id: 52, user_email: 'Paul@mail.com'})]
我看到一些使用done()函数的例子,但我不知道它是如何用它来测试这个异步函数的。你能帮我解决一下这个错误吗?