简体   繁体   English

来自组件的角度单元测试spyOn服务

[英]Angular unit-testing spyOn service from component

I've got a login component and I want to test it whether it calls the service's method with proper values, however I don't know how to spy on that service from the component. 我有一个登录组件,我想测试它是否以正确的值调用服务的方法,但是我不知道如何从组件中监视该服务。

I've tried 我试过了

beforeEach(() => {
...
authService = TestBed.get(AuthService);
});

And this is not working 这是行不通的

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');
    });
});

It says 它说

An error was thrown in afterAll Expected spy signInByLogin to have been called with [ 'test', 'password' ] but actual calls were [ '', '' ]. 使用['test','password']调用afterAll Expected spy signInByLogin引发错误,但实际调用为[”,”]。

The service's method is called from the private function in login component. 该服务的方法是从登录组件中的私有函数调用的。 And the call is 电话是

this.authService
            .signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)

The spying works fine. 间谍工作正常。 As you can see from the error message, the service is being called, but it's called with empty strings instead of the values of the input fields. 从错误消息中可以看到,正在调用该服务,但是使用空字符串而不是输入字段的值来调用该服务。

You change the value of the inputs, but you never emit any event, so Angular has no idea that the value has changed and this it must modify its model. 您可以更改输入的值,但不会发出任何事件,因此Angular不知道值已更改,因此必须修改其模型。 You need to add something like 您需要添加类似

username.nativeElement.dispatchEvent(new Event("imput));

(same for the other input of course). (当然与其他输入相同)。

Shameless plug: this wouldn't be necessary, and the code of the test would be more readable if you used ngx-speculoos . 无耻的插件:这不是必需的,并且如果您使用ngx-speculoos ,则测试的代码将更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM