[英]Unit test case: expect a component function to have been called from a constructor
I have the following component:我有以下组件:
export class MyComponent {
constructor() { this.getStorageData(); }
getStorageData() {...}
}
I am trying to test the following case: after creation of the component, the function getStorageData
should have been called.我正在尝试测试以下情况:在创建组件后,应该调用函数
getStorageData
。 This is how I tried to do it:这就是我尝试这样做的方式:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
})
it('should create', async(()=> {
var spy = spyOn(component, "getStorageData").and.callThrough();
fixture.detectChanges();
expect(component).toBeDefined();
expect(component.getStorageData).toHaveBeenCalled();
}))
The last line of the test always fails the test.测试的最后一行始终未通过测试。 What am I doing wrong?
我究竟做错了什么?
The reason it has not been called, is because the spyOn
method is called after component creation, so after the constructor has been called.之所以没有被调用,是因为
spyOn
方法是在组件创建之后调用的,所以在构造函数被调用之后。 There are a couple ways around this:有几种方法可以解决这个问题:
ngOnInit
hook:ngOnInit
钩子:export class MyComponent {
constructor() {}
ngOnInit(): void {
this.getStorageData();
}
getStorageData() {...}
}
And you just make sure you call the spyOn
before your first detectChanges()
.并且您只需确保在您的第一个
detectChanges()
之前调用spyOn
。 Then you can leave the test just as you have it然后你就可以离开考试了
new
and add the spy to the prototype:new
初始化组件并将 spy 添加到原型中:it('should call getStorageData', function() {
spyOn(MyComponent.prototype, 'getStorageData').and.callThrough();
const component = new MyComponent();
expect(MyComponent.prototype.getStorageData).toHaveBeenCalled();
});
You will have supply any possible constructor providers yourself, as dependency injection will not work您将自己提供任何可能的构造函数提供者,因为依赖注入将不起作用
beforeEach
on the prototypebeforeEach
beforeEach(() => {
spyOn(MyComponent.prototype, 'getStorageData').and.callThrough();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
})
it('should create', async(()=> {
fixture.detectChanges();
expect(component).toBeDefined();
expect(MyComponent.prototype.getStorageData).toHaveBeenCalled();
}))
You should probably look into isolating this test, to be sure it's not spied with every test in this spec.您可能应该考虑隔离此测试,以确保它不会在本规范中的每个测试中都被监视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.