angularunit-testingjasmineangular-signals

How to test Angular's output signal?


I have an output signal in my component like this:

updatedBook = output<Book>();
...
updateBook(changedBook: Book){
    this.updatedBook.emit(changedBook);
}

In the template I have a binding like this:

<my-component
(updatedBook)="onBookUpdate($event)"
></my-component>

And in the parent component I use the emitted value like this:

onBookUpdate(updatedBook: Book) {
    this.book = Book;
}

How can I write a unit test for it in the child component? I would like to verify that the updatedBook.emit() was called.


Solution

  • You can use jasmine's spyOn function:

    it('should emit the updatedBook event', () => {
      const spy = spyOn(component.updatedBook, 'emit');
      const book: Book = {}:
      component.updateBook(book);
    
      expect(spy).toHaveBeenCalledOnceWith(book);
    });