问题描述
限时送ChatGPT账号..在我的控制器中,我定义了以下服务:
In my Controller I've defined the following service:
CrudService.getAllGroups().$promise.then(
function (response) { $scope.groups = response; },
function (error) { //error code.. }
);
好吧,我想测试这个服务是否得到响应.首先在测试脚本中,我定义了一个函数来检查是否完全定义了服务.
Well, I want to test this service whether it gets a response or not. In test script at first I've defined a function to check whether the service is defined at all.
测试代码:
describe('Ctrl: TestCtrl', function () {
beforeEach(module('testApp'));
var scope,
CrudService,
ctrl,
backend;
beforeEach(inject(function ($controller, $rootScope, _CrudService_, $httpBackend) {
scope = $rootScope.$new();
ctrl = $controller('TestCtrl', {
$scope: scope
});
CrudService = _CrudService_;
backend = $httpBackend;
}));
it('should defined the service getGroups', function () {
expect(CrudService.getGroups).toBeDefined();
});
//this is wrong!
it('should returns a successful response', function () {
backend.expectGET('http://localhost:63831/api/group').respond(200, 'success');
backend.flush();
});
});
我不知道如何在测试中获得响应.我是单元测试的新手,需要一些帮助.
I don't know how to get a response in the test. I'm new in unit testing and need some help.
为了更好地理解这里是服务代码:
For a better comprehension here is the service code:
//CrudService file:
...
return {
getAllGroups: function () {
return ResService.group.query();
}
}
...
//ResService file:
return {
group: $resource(baseUrl + '/api/group/:Id', {
Id: '@Id'
}, {})
}
有人有想法吗?
推荐答案
它不是单元测试,这是不正确的.如果您在这里测试控制器,那么您应该模拟 CrudService
并测试 $scope.groups
是否已正确分配.
It's incorrect in the sense that it's not a unit test. If you are testing controller here, then you should mock CrudService
and test that $scope.groups
has been assigned correctly.
beforeEach(function () {
module(function ($provide) {
$provide.factory('CrudService', function () {
return {
getAllGroups: function () {
return {
$promise: null // return an actual promise here
}
}
}
});
});
});
it('should set groups', function () {
expect($scope.groups).toEqual('success')
});
并且您需要一个单独的规范来测试 CrudService
是否正确调用后端.
And you need a separate spec to test if CrudService
calling backend correctly.
这篇关于使用 AngularJS 中的 Jasmine 对 Controller 中的服务进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论