[英]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.