I am using Angular / Jasmine for unit tests.
Currently I am testing a component with an Input field + "Add" button.
"Add" should call a add() function with a service behind it.
I want to test if the service method was called.
I have two test for this.
One is working, (Add value to Input field & click the "Add" Button)
One is not working. (calling the add() method directly behind the "Add" Button)\
The error ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe') indicates that the service is undefined. But I don't understand why the service is in one testcase defined and in the other not?
Here is a Stackblitz with Jasmine-Test : https://stackblitz.com/edit/angular-ivy-dnzv96?file=src/app/app.component.spec.ts
HTML
<div>
<label>Hero name:
<input #heroName />
</label>
<button (click)="add(heroName.value)">
add
</button>
</div>
The add() method
add(name: string): void {
this.heroService.addHero({ name })
.subscribe(hero => {
this.heroes.push(hero);
});
}
The two Test
describe('should call HeroService.addHero()',() => {
**// WORKING TEST**
it('by using input dialog and click "Add" button', () => {
const input = el.query(By.css('input')).nativeElement;
input.value = 'NewHero';
const button = el.query(By.css('button'));
button.triggerEventHandler('click', null)
fixture.detectChanges;
expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'NewHero' } );
})
**// FAILING TEST - ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe')**
it('by calling method add()', (() => {
component.add('newHero');
expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'NewHero'} );
}))
})