【问题标题】:Injecting mock services with @testing-library/angular使用 @testing-library/angular 注入模拟服务
【发布时间】:2019-10-25 15:11:06
【问题描述】:

我正在尝试使用 Kent C Dodds 的 @testing-library/angular 来测试角度组件。我的组件依赖于 Angular 服务。我在 api 文档中没有看到有关如何注入模拟服务以为我的单元测试提供模拟数据的信息。

    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'));
  });
});
````````````

【问题讨论】:

  • 你好 :) 你能提供测试代码吗?
  • 本,请提供更多信息。
  • 使用HttpTestingController

标签: angular angular-testing-library


【解决方案1】:

您可以使用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

【讨论】:

猜你喜欢
  • 2021-03-22
  • 2018-11-21
  • 2021-07-16
  • 2021-01-13
  • 2020-05-26
  • 2023-03-17
  • 2015-12-02
  • 2020-08-01
  • 2019-10-30
相关资源
最近更新 更多