[英]Angular unit-testing spyOn service from component
我有一個登錄組件,我想測試它是否以正確的值調用服務的方法,但是我不知道如何從組件中監視該服務。
我試過了
beforeEach(() => {
...
authService = TestBed.get(AuthService);
});
這是行不通的
it('should pass proper values', () => {
const submitSpy = spyOn(authService, 'signInByLogin');
const loginSpy = spyOn(component, 'signIn').and.callThrough();
const username = fixture.debugElement.query(By.css('#username'));
const password = fixture.debugElement.query(By.css('#password'));
const submitBtn = fixture.debugElement.query(By.css('[type="submit"]'));
username.nativeElement.value = 'test';
password.nativeElement.value = 'password';
fixture.detectChanges();
expect(username.nativeElement.value).toBe('test');
expect(password.nativeElement.value).toBe('password');
expect(submitBtn).toBeTruthy();
fixture.detectChanges();
submitBtn.triggerEventHandler('click', null);
fixture.whenStable().then(() => {
expect(loginSpy).toHaveBeenCalled();
expect(submitSpy).toHaveBeenCalledWith('test', 'password');
});
});
它說
使用['test','password']調用afterAll Expected spy signInByLogin引發錯誤,但實際調用為[”,”]。
該服務的方法是從登錄組件中的私有函數調用的。 電話是
this.authService
.signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)
間諜工作正常。 從錯誤消息中可以看到,正在調用該服務,但是使用空字符串而不是輸入字段的值來調用該服務。
您可以更改輸入的值,但不會發出任何事件,因此Angular不知道值已更改,因此必須修改其模型。 您需要添加類似
username.nativeElement.dispatchEvent(new Event("imput));
(當然與其他輸入相同)。
無恥的插件:這不是必需的,並且如果您使用ngx-speculoos ,則測試的代碼將更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.