使用jasmine模拟函数调用

时间:2014-08-26 15:01:33

标签: javascript angularjs unit-testing jasmine hottowel

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

我试图在我的控制器中测试一个正好调用另一个名为" log"的函数的函数。这" log"是一个存储在私有变量中的函数,它从名为" common"的依赖项中获取其值。

我知道我可能需要以某种方式存根这个功能,但我不确定这个特定的例子从哪里开始,因为我对angularjs,茉莉是个新手,等等。任何想法都赞赏

单元测试

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'不是一项功能(评估'记录('删除附件:' + attachment.FileName)')

2 个答案:

答案 0 :(得分:5)

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

您可能不想传递常用服务,但创建一个返回函数的存根。

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

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

你现在可以用:

监视它
spyOn(wrapper, 'logger');

答案 1 :(得分:2)

在removeAttachment之前调用var log = getLogFn(controllerId)? getLogFn()是否被注入控制器?如果这两个都是真的,你可以将getLogFn()存根,以返回一个可用于测试的虚拟日志对象。我不知道hottowel,我使用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);