简体   繁体   中英

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 [ '', '' ].

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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