【发布时间】:2021-12-31 16:29:48
【问题描述】:
我正在使用 Angular / Jasmine 进行单元测试。
目前我正在测试一个带有输入字段+“添加”按钮的组件。
“添加”应该调用一个 add() 函数,其背后有一个服务。
我想测试是否调用了服务方法。
我对此有两个测试。
一个正在工作,(将值添加到输入字段并单击“添加”按钮)
一个不工作。 (直接在“添加”按钮后面调用 add() 方法)\
错误ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe')表示服务未定义。但我不明白为什么服务在一个测试用例中定义而在另一个测试用例中没有?
这是一个带有 Jasmine-Test 的 Stackblitz: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>
add() 方法
add(name: string): void {
this.heroService.addHero({ name })
.subscribe(hero => {
this.heroes.push(hero);
});
}
两个测试
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'} );
}))
})
【问题讨论】:
标签: angular typescript unit-testing jasmine