我有一个这样的功能
$scope.openMail=function(mail){
DocumentTypes.getDocument(function(response){
$scope.documentTypes=response.result;
$log.log("documentTypes",$scope.documentTypes);
})
}
上述乐趣的规范是
it("should test open mail", function(){
scope.documentTypes=[{"type":"pdf"},{"type":"xml"}];
spyOn(documentTypes,"getDocument").and.callFake(function(){
return scope.documentTypes;
});
var mail='back';
scope.openMail(mail);
expect(scope.documentTypes).toEqual({"type":"pdf"},{"type":"xml"});
})
因此代码未涵盖function(response){}
最佳答案
您的测试有几个问题:
- 您执行
spyOn(documentTypes,"getDocument")
而不是spyOn(DocumentTypes,"getDocument")
- 您的假函数返回一个值(同步),而不是调用提供的回调(异步)
- 首先将
scope.documentTypes
初始化为测试的预期结果,即无论代码做什么,测试都会通过(除非出现异常) - 您的代码存在更多问题 - 您正在测试的函数对输入
mail
参数没有任何作用
这是我测试它的方法:
describe('$scope.openMail', function() {
beforeEach(function() {
spyOn(DocumentTypes, 'getDocument');
});
it('uses DocumentTypes.getDocument service to get the document types', function() {
$scope.openMail('test_mail');
expect(DocumentTypes.getDocument).toHaveBeenCalledWith(jasmine.any(Function));
});
describe('provides a callback function that', function() {
beforeEach(function() {
DocumentTypes.getDocument.and.callFake(function (callback) {
callback('test_document_types');
});
});
it('stores the document types on the scope', function() {
$scope.openMail('test_mail');
expect($scope.documentTypes).toEqual('test_document_types');
});
// Note: This is optional, depending on whether you test logging or not
it('logs the document types', function() {
spyOn($log, 'log');
$scope.openMail('test_mail');
expect($log.log).toHaveBeenCalledWith('documentTypes', 'test_document_types');
});
});
});
关于angularjs - Karma 中服务调用成功响应的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47301711/