开始使用HotTowelAngular模板,我正在设置单元测试.陷入困境.
我正在尝试在我的控制器中测试一个正好调用另一个名为"log"的函数的函数.这个"log"是一个存储在私有变量中的函数,它从一个名为"common"的依赖项中获取它的值.
我知道我可能需要以某种方式存根这个函数,但我不确定从哪个特定的例子开始,因为我对angularjs,jasmine等等都很新.任何想法都表示赞赏
单元测试:
describe("quote", function () { var scope, controller, common; beforeEach(inject(function($rootScope, $controller, _common_) { scope = $rootScope.$new(); common = _common_; controller = $controller; })); describe("removeAttachment", function() { it("should remove the attachment when requested", function() { var vm = controller("quote", { $scope: scope }); vm.attachmentList.push({ FileName: "file1", FileAsString: "..." }); vm.attachmentList.push({ FileName: "file2", FileAsString: "..." }); vm.attachmentList.push({ FileName: "file3", FileAsString: "..." }); expect(vm.attachmentList.length).toEqual(3); // here's the call where it fails vm.removeAttachment(vm.attachmentList[1]); expect(vm.attachmentListCount).toEqual(2); expect(vm.attachmentList.length).toEqual(2); expect(vm.attachmentList[1].FileName).toBe("file3"); }); }); });
控制器:
var getLogFn = common.logger.getLogFn; var log = getLogFn(controllerId); function removeAttachment(attachment) { // need to stub this out log('removing attachment: ' + attachment.FileName); vm.attachmentList.splice(vm.attachmentList.indexOf(attachment), 1); vm.attachmentListCount = vm.attachmentList.length; }
来自Jasmine 的错误:
TypeError:'undefined'不是函数(评估'log('删除附件:'+ attachment.FileName)')
在你的测试中你应该有controller = $ contoller("YourController",{它的依赖项});
您可能不希望传递公共服务,但创建一个返回函数的存根.
var wrapper = {logger: function () {}}; var stub = { logger: { getLogFun: function() {return wrapper.logger} }};
您可以通过它代替您的共同服务.
你现在可以通过以下方式监视它:
spyOn(wrapper, 'logger');