Angular 来自组件的单元测试 spyOn 服务
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');
});
});
它说
An error was thrown in afterAll
Expected spy signInByLogin to have been called with [ 'test', 'password' ] but actual calls were [ '', '' ].
服务的方法是从登录组件中的私有函数调用的。
电话是
this.authService
.signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)
间谍工作正常。正如您从错误消息中看到的那样,正在调用该服务,但它是用空字符串而不是输入字段的值调用的。
您更改了输入的值,但您从未发出任何事件,因此 Angular 不知道值已更改,因此它必须修改其模型。您需要添加类似
的内容
username.nativeElement.dispatchEvent(new Event("imput));
(当然其他输入也一样)。
不要脸的外挂:这个没必要,用ngx-speculoos.
测试代码可读性更好
我有一个登录组件,我想测试它是否使用正确的值调用服务的方法,但是我不知道如何从该组件监视该服务。
我试过了
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');
});
});
它说
An error was thrown in afterAll Expected spy signInByLogin to have been called with [ 'test', 'password' ] but actual calls were [ '', '' ].
服务的方法是从登录组件中的私有函数调用的。 电话是
this.authService
.signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)
间谍工作正常。正如您从错误消息中看到的那样,正在调用该服务,但它是用空字符串而不是输入字段的值调用的。
您更改了输入的值,但您从未发出任何事件,因此 Angular 不知道值已更改,因此它必须修改其模型。您需要添加类似
的内容username.nativeElement.dispatchEvent(new Event("imput));
(当然其他输入也一样)。
不要脸的外挂:这个没必要,用ngx-speculoos.
测试代码可读性更好