3

I am trying to test an angular component using @testing-library/angular by Kent C Dodds. My component has a dependency on an Angular service. I see no information in the api docs on how to inject a mock service to provide mock data for my unit test.

    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'));
  });
});
````````````
timdeschryver
  • 14,415
  • 1
  • 19
  • 32

1 Answers1

5

You can use providers to provide a service (just like you can do with TestBed)

const component = await render(AppComponent, {
    providers: [
      {
        provide: TodoProviderService,
        useValue: { getTodos: ... },
      },
    ],
  });

More examples at: https://github.com/testing-library/angular-testing-library/tree/master/src/app/examples

timdeschryver
  • 14,415
  • 1
  • 19
  • 32
  • 2
    [Updated link](https://github.com/testing-library/angular-testing-library/blob/main/apps/example-app/src/app/examples/12-service-component.spec.ts) – Christian Jensen Sep 23 '21 at 22:19