角度服务的Jasmine单元测试在控制器中 [英] Jasmine unit test for angular service In controller
问题描述
我是茉莉花框架的新手。我已经完成了一些教程并学习并开始编写单元测试。 这里面临的一个问题是描述。
我有一个控制器,我可以调用服务调用来获取数据。请参阅下面的代码。
I'm new to jasmine framework. I've gone through some tutorials and learned and started writing unit tests. 'facing one issue here is the description. I have a controller where i can invoke a service call to get the data. See the code below.
$scope.getEmpInfo = function() {
EmpService.getInfo($scope.empid)
.then(function(data) {
$scope.empData = data;
$scope.populateEmpData($scope.empData);
}, function(reason) {
//do nothing
}
}
现在,我我想为上面的方法编写一个单元测试。我可以使用promise对serice进行间谍,但是我无法监视 $ scope.populateEmpData()
。这是我的测试用例。
Now, i want to write a unit test for the above method. Im able to make a spy on serice using promise but i wasnt able to spy $scope.populateEmpData()
. here is my test case.
describe('Emp data', function() {
var d, scope;
beforeEach(function() {
module("emp");
module("emo.info");
});
describe('empcontroller', function() {
beforeEach(inject(function($q,_EmpService_, $controller,$rootScope){
d = $q.defer();
empService = _EmpService_;
spyOn(empService,"getInfo").and.returnValue(d.promise);
scope = $rootScope.$new();
empCtrl = $controller("empController", {
$scope: scope,
});
}));
it('should get the Employee information ', function() {
scope.getEmpInfo();
spyOn(scope,'populateEmpData');
expect(EmpService.getInfo).toHaveBeenCalled();
//Here im getting the error.
expect(scope.populateEmpData).toHaveBeenCalled();
});
});
});
请帮助解决此问题。在此先感谢。
Please help resolve this issue. Thanks in advance.
推荐答案
这是因为你没有解决承诺。你必须在spyOn中进行更改。
It's because you are not resolving promise. You will have to make change in spyOn.
- spyOn(empService,"getInfo").and.callFake(function() {
return {
then : function(success, error) {
success();
}
} }
Now, it will go into the success callback and will try to call $scope.populateEmpData();
这篇关于角度服务的Jasmine单元测试在控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!