您好 stackoverflow 社区。p>
我正在开发一个 Angular 项目 (1.5.6),使用组件结构,目前正在编写一些单元测试。我仍在学习很多关于单元测试的知识——尤其是与 Angular 相关的知识——并且希望我能就以下问题向您寻求帮助:
我尝试测试一个组件,该组件从其父组件接收回调方法。我正在尝试模拟该方法 foo
(参见下面的代码示例)。 不幸这个方法会调用父 Controller 。
所以当我尝试测试它时,它提示该方法未定义。然后我想我可以用 spy On来模拟它,但后来我得到错误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);
});
});
我希望我没有为此添加任何错误,但是上面的内容大约是我想要做的。欢迎任何建议,如果方法错误或需要更多信息,请告诉我!
最佳答案
在 @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);
});
我使用的一些其他来源是:
关于angularjs - 如何对调用父组件方法的组件中的函数进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621944/