我正在使用 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'} );
}))
})
uj5u.com熱心網友回復:
您沒有從mockHeroServicespy回傳資料,因此會出現錯誤。在規范檔案中,您可以進行修改:
const hero = {
id: 1,
name: 'NewHero',
strength: 80,
}
// within describe
it('by using input dialog and push add button', () => {
const stubValue = 'NewHero';
mockHeroService.addHero.and.returnValue(of(hero));
// existing logic
expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'NewHero' } );
})
it('by calling method add()', (() => {
const stubValue = 'newHero';
mockHeroService.addHero.and.returnValue(of(hero));
component.add('newHero');
expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'newHero'} );
}))
同樣在ts檔案中,您可以添加一個if陳述句來防止 null/undefined 為:
this.heroService.addHero({ name })
.subscribe(hero => {
if (this.heroes) {
this.heroes.push(hero);
}
});
uj5u.com熱心網友回復:
錯誤 ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe') 表示服務未定義。但我不明白為什么服務在一個定義的測驗用例中,而在另一個沒有?
我認為情況并非如此:錯誤表明服務已定義,addMethod 被呼叫,但回傳的值是未定義的,而不是一個Observable:
this.heroService.addHero({ name }) // this is fine
.subscribe(...); // this is not
所以,我認為問題在于你如何設定你的 mockHeroService,我猜你沒有在模擬addHero方法中回傳任何東西。
uj5u.com熱心網友回復:
感謝 Chiesa 和 Siddhant。
基耶薩解釋了錯誤。Siddhants 提出了一個解決方案。沒什么好補充的。
這是作業示例。
https://stackblitz.com/edit/angular-ivy-p1ccau?file=src/app/app.component.spec.ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/400345.html
