如何在调用父组件方法的组件中对函数进行单元测试

时间:2016-11-16 00:09:36

标签: angularjs unit-testing

Hello stackoverflow社区。

我正在研究Angular项目(1.5.6),使用组件结构并且当前正在编写一些单元测试。我还在学习很多关于单元测试的知识 - 尤其是与Angular相关的 - 并且希望我可以请求你帮助解决以下问题:

我尝试测试一个组件,它从它的父组件接收回调方法。我试图模拟方法foo(参见下面的代码示例)。并且遗憾的是这个方法会调用父控制器。

因此,当我尝试测试它时,它抱怨说,该方法是未定义的。然后我想我可以用spyOn来模拟它,但后来我得到了错误Error: <spyOn> : foobar() method does not exist

所以我认为我无法模仿那种方法。

模块:

angular.module("myApp")
.component("sample", {
    "templateUrl": "components/sample/sample.html",
    "controller": "SampleController",
    "controllerAs": "sampleCtrl",
    "bindings": {
        "config": "<",
        "foobar": "&"
    }
})
.controller("SampleController",
           ["$scope",
    function($scope) {
        this.isActive = true;

        this.foo = function() {
             // do stuff
             this.isActive = false;

             // also do
             this.foobar();
        };
    }
);

单元测试

describe("Component: SampleComponent", function() {

    beforeEach(module("myApp"));

    var sampleComponent, scope, $httpBackend;

    beforeEach(inject(function($componentController, $rootScope, _$httpBackend_) {
        scope = $rootScope.$new();
        sampleComponent = $componentController("sample", {
            "$scope": scope
        }); 
        $httpBackend = _$httpBackend_;
    }));

    it("should do set isActive to false on 'foo' and call method...", function() {
        spyOn(sampleComponent, "foobar")

        expect(sampleComponent.isActive).toBe(true);
        expect(sampleComponent).toBe("");
        expect(sampleComponent.foobar).not.toHaveBeenCalled();

        sampleComponent.foo();

        expect(sampleComponent.foobar).toHaveBeenCalled();
        expect(sampleComponent.foobar.calls.count()).toBe(1);
        expect(sampleComponent.isActive).toBe(false);
    });
});

我希望我没有添加任何错误,但上面的我想要做的事情。欢迎提出任何建议,如果方法错误或需要更多信息,请告诉我们!

1 个答案:

答案 0 :(得分:2)

在@estus的帮助下(参见相关评论) - 我了解到我可以使用createSpy来解决这个问题。

    it("should do set isActive to false on 'foo' and call method...", function() {
        sampleComponent.foobar = jasmine.createSpy();

        expect(sampleComponent.isActive).toBe(true);
        expect(sampleComponent).toBe("");
        expect(sampleComponent.foobar).not.toHaveBeenCalled();

        sampleComponent.foo();

        expect(sampleComponent.foobar).toHaveBeenCalled();
        expect(sampleComponent.foobar.calls.count()).toBe(1);
        expect(sampleComponent.isActive).toBe(false);
    });

我使用的其他一些来源是:

相关问题