我正在尝试使用 Kent C Dodds 的 @testing-library/angular 测试 Angular 组件。我的组件依赖于 Angular 服务。我在 api 文档中看不到有关如何注入(inject)模拟服务以为我的单元测试提供模拟数据的信息。
export class ItemCounterComponent implements OnInit {
public availableTodoCount: number;
constructor(private todoProviderService: TodoProviderService) {
this.todoProviderService.getTodos().subscribe(todos => {
this.availableTodoCount = todos.filter(todo => !todo.completed).length;
});
}
ngOnInit() {
}
}
describe('ItemCounterComponent', () => {
it('shows the count correctly', async () => {
const { getByText } = await render(ItemCounterComponent, { componentProperties: { availableTodoCount: 5 } });
expect (getByText('5 items left'));
});
});
````````````
最佳答案
您可以使用providers
来提供服务(就像您可以使用 TestBed 一样)
const component = await render(AppComponent, {
providers: [
{
provide: TodoProviderService,
useValue: { getTodos: ... },
},
],
});
更多示例位于:https://github.com/testing-library/angular-testing-library/tree/master/src/app/examples
关于angular - 使用@testing-library/angular 注入(inject)模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56539580/