下面是我的代码,我不想调用服务函数,所以我使用间谍,但它给出了错误。我无法弄明白。
'use strict';
describe('Testing DetailCtrl\n\n\n', function() {
beforeEach(module("safe-repository"));
var $controller, $scope, controller;
var services = {
documentService:null
};
// Initialization before tests
beforeEach(inject(function(_$controller_, _documentService_){
$controller = _$controller_;
$scope = {};
controller = $controller('DetailCtrl', { $scope: $scope });
services.documentService=_documentService_;
spyOn(services.documentService, 'deleteDocument').and.callFake(function(){
console.log("inside delete function");
});
}));
describe('Testing self.deleteFile() function for different test cases\n\n', function() {
it(' When user has access permission to delete file/doc', function(done) {
expect(services.documentService.deleteDocument).toHaveBeenCalled();
// Inform jasmine that the test finish here
done();
});
});
});
感谢任何帮助。
答案 0 :(得分:0)
你不需要......
var services = {
documentService:null
};
该代码只是令人困惑。
你应该将其简化为......
// services.documentService=_documentService_; // WHY DO THIS??
documentService=_documentService_;
然后......
spyOn(documentService, 'deleteDocument').and.callFake ... etc
然后......
expect(documentService.deleteDocument).toHaveBeenCalled();
你可能也想尝试......
spyOn(loginService, 'isSuperAdmin').and.returnValue("something");
INSTEAD OF callFake(你的期望陈述将保持不变)
另外......
我假设您的控制器在构建期间正在调用此方法?例如,以下行在施工期间进行预期的呼叫?
controller = $controller('DetailCtrl', { $scope: $scope });
换句话说,你的控制器应该看起来像......
app.controller("DetailCtrl", function($scope, documentService) {
// some other code
documentService.deleteDocument(); // MAKE SURE THIS CODE IS ACTUALLY BEING HIT IF ITS WRAPPED IN A CONDITIONAL STATEMENT
// some other code
});
答案 1 :(得分:0)
试试这个,它可能对你有所帮助:)。
'use strict';
describe('Testing DetailCtrl\n\n\n', function() {
var $controller, scope, ctrl, mockService;
beforeEach(module("safe-repository"));
beforeEach(inject(function($rootScope, _$controller_){
scope = $rootScope.$new();
function del() {
//your return value
}
mockService = {
deleteDocument: del
}
$controller = _$controller_;
}));
function initController(){
ctrl = $controller('DetailCtrl', {
$scope: scope,
documentService: mockService
});
}
it(' When user has access permission to delete file/doc', function() {
spyOn(documentService,'deleteDocument').and.callThrough();
initController();
expect(mockService.deleteDocument).toHaveBeenCalled();
});
});
});