How to test if a method is called when the input event is emitted?

Viewed 21

I have an input field.

  <input id-"search-text" (input)="search()">

unit test as follows.

it('search ', fakeAsync(() => {
       
         spyOn(component, "search").and.callThrough();
        
          let input = fixture.debugElement.query(By.css('#search-text'));
          let el = input.nativeElement;
          el.value = 'Fake One';
          el.dispatchEvent(new Event('#search-text'));
         
          expect(component.search).toHaveBeenCalled();
          flush()
       
      }));

I was trying to call function search while the input field got triggered. But am getting error as

Expected spy search to have been called.
1 Answers

I recommend you to use Angular Testing Library, it can make your tests quite simpler.

This is how you would write this test using it:

it('should be able to search', async () => {
  spyOn(component, 'search').and.callThrough();

  const input = await screen.findByRole('textbox');

  userEvent.type(input, 'Fake one');

  expect(component.search).toHaveBeenCalled();
})
Related