当前位置:   jquery > 正文

使用jasmine模拟函数调用

javascript,unit-testing,jasmine,angularjs,hottowel,DevBox,在线流程图,编程,编程问答,程序员,开发者工具,开发工具,json解析,二维码生成,unix时间戳,在线开发工具,前端开发工具,开发人员工具,站长工具

开始使用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)')



1> Martin..:

在你的测试中你应该有controller = $ contoller("YourController",{它的依赖项});

您可能不希望传递公共服务,但创建一个返回函数的存根.

var  wrapper = {logger: function () {}};
var stub = { logger: { getLogFun: function() {return wrapper.logger} }};

您可以通过它代替您的共同服务.

你现在可以通过以下方式监视它:

spyOn(wrapper, 'logger');

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/jquery/detail/13255
推荐阅读
相关标签
  

闽ICP备14008679号