Angular-如何使用异步服务调用对组件进行单元测试 [英] Angular - How to unit test component with asynchronous service call
本文介绍了Angular-如何使用异步服务调用对组件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下组件,可从Angular服务检索数据:
I have the following component which retrieves data from an Angular service:
export class MyComponent {
constructor() {
myService.get().then(() => {
console.log('hello from constructor');
});
}
}
然后是我的单元测试:
///////////
it('does something', () => {
console.log('hello from unit test');
});
///////////
不幸的是,这导致出现以下日志:
Unfortunately this results in the following log:
> hello from unit test
> hello from constructor
如何在运行单元测试之前确保构造函数完成?
How can I make sure that the constructor finishes before running the unit test?
推荐答案
请勿使用构造函数加载数据,而应实现OnInit
接口.
Do not use the constructor to load data, implement the OnInit
interface instead.
import { OnInit } from '@angular/core';
export class MyComponent implements OnInit {
constructor(private myService: MyService) {}
ngOnInit() {
myService.get().then(() => {
console.log('hello from constructor');
});
}
}
- 另请参见角度文档生命周期挂钩.
- 别忘了像
myService
实例一样注入依赖项,我将其添加到了构造函数中. - See also the angular documentation Lifecycle Hooks.
- Do not forget to inject your dependencies like your
myService
instance, I added it to the constructor.
我建议您阅读测试文档.这是很多信息,但这是值得的.这是用于单元测试组件的代码.
I recommend you read over the Testing documentation. It is a lot of information but it is worth it. Here is code that you would use to unit test your component.
let comp: MyComponent ;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{ provide: MyService, useValue: {} }
]
})
.compileComponents();
TestBed.compileComponents();
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
}));
it('initializes the component', fakeAsync(() => {
var service = TestBed.get(MyService); // get your service
service.get = () => {
return Promise.resolve(); // you can pass data here if the service returns something
};
// here you could add an expect to validate component state before the call or service completes
comp.ngOnInit(); // call ngOnInit
tick(); // simulate the promise being resolved
expect(service.get.toHaveBeenCalled);
// here you could add an expect to validate component state after the service completes
}));
这篇关于Angular-如何使用异步服务调用对组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文