Ben Du Plessis
Ben Du Plessis

Reputation: 39

Injecting mock services with @testing-library/angular

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

Upvotes: 3

Views: 2363

Answers (1)

timdeschryver
timdeschryver

Reputation: 15525

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

Upvotes: 5

Related Questions