Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'));
  });
});
````````````
like image 252
Ben Du Plessis Avatar asked Jul 11 '26 08:07

Ben Du Plessis


1 Answers

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

like image 75
timdeschryver Avatar answered Jul 15 '26 11:07

timdeschryver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!