用@ testing-library / angular注入模拟服务

时间:2019-06-11 08:32:59

标签: angular

我正在尝试使用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'));
  });
});
````````````

1 个答案:

答案 0 :(得分:0)

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