gpt4 book ai didi

Angular - 如何使用异步服务调用对组件进行单元测试

转载 作者:行者123 更新时间:2023-12-05 03:07:39 25 4
gpt4 key购买 nike

我有以下从 Angular 服务中检索数据的组件:

export class MyComponent {
constructor() {
myService.get().then(() => {
console.log('hello from constructor');
});
}
}

然后是我的单元测试:

///////////

it('does something', () => {
console.log('hello from unit test');
});

///////////

不幸的是,这会导致以下日志:

> hello from unit test
> hello from constructor

如何确保构造函数在运行单元测试之前完成?

最佳答案

不要使用构造函数加载数据,而是实现OnInit接口(interface)。

import { OnInit } from '@angular/core';
export class MyComponent implements OnInit {

constructor(private myService: MyService) {}

ngOnInit() {
myService.get().then(() => {
console.log('hello from constructor');
});
}
}
  • 另请参阅 Angular 文档 Lifecycle Hooks .
  • 不要忘记注入(inject)您的依赖项,例如您的 myService 实例,我已将其添加到构造函数中。

测试

我建议您阅读 Testing documentation .这是很多信息,但值得。这是您将用于对组件进行单元测试的代码。

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 - 如何使用异步服务调用对组件进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46914105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com