【问题标题】:mock a function call using jasmine使用 jasmine 模拟函数调用
【发布时间】:2014-08-26 15:01:33
【问题描述】:

开始使用HotTowelAngular 模板,我正在设置单元测试。陷入困境。

我正在尝试在我的控制器中测试一个函数,该函数恰好调用了另一个名为“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' is not a function(评估 'log('removing attachment: ' + attachment.FileName)')

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine hottowel


    【解决方案1】:

    在您的测试中,您应该有 controller = $contoller("YourController", {it's dependencies});

    您可能不想传入您的common 服务,而是创建一个返回函数的存根。

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

    您可以通过它来代替您的公共服务。

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

    spyOn(wrapper, 'logger');
    

    【讨论】:

      【解决方案2】:

      var log = getLogFn(controllerId) 是否在 removeAttachment 之前被调用? getLogFn() 是否注入到控制器中?如果这两个都是真的,你可以存根 getLogFn() 来返回一个你可以用于测试的虚拟日志对象。我不知道热毛巾,我使用Sinon。在Sinon,我会打电话

      var getLogFnStub = sinon.stub().returns(function (msg) { return 1;/*My expected result*/ });

      并将其传递给您的控制器,例如

      var vm = controller("quote", { $scope: scope, getLogFn: getLogFnStub});

      如果你愿意,你可以对你在Sinon 中创建的存根进行断言,就像这样

      sinon.assert.called(getLogFnStub);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-11
        • 1970-01-01
        相关资源
        最近更新 更多