0

Component function:

onSubmit() {
    this.formDataService.sendUserCredentials(this.loginForm.get('email').value, 
    this.loginForm.get('password').value)
    .subscribe(res => {
        localStorage.setItem('X-Auth-Token', res.headers.get('X-Auth-Token'));
        localStorage.setItem('Authorization', res.headers.get('Authorization'));
        localStorage.setItem('userObject', JSON.stringify(res.body));
        this.router.navigate(['dashboard']);
    }, err => {
      this.invalidCredentials = true;
    });
}

Service Method:

sendUserCredentials(userEmail, userPassword) {
    const userCredentials = {
        email: userEmail,
        password: (jsSha.sha512(userPassword)).toUpperCase(),
    };

    return this.http.post(environment.BASE_URL + 'users/login', userCredentials, {
        observe: 'response',
        headers: new HttpHeaders().set('Authorization', 'dfsdf-e4vfd-ertrg')
    });
}

Unit test:

it('API call inside onSubmit resolves successfully', fakeAsync(() => {
    const spy = spyOn(service, 'sendUserCredentials').and.returnValue(of('logged-in'));
    component.onSubmit();
    tick();
    expect(spy.calls.any()).toBe(true);
}));

I am able to pass through the line where a service method named as sendUserCredentials but inside that service method there is a line where I am fetching headers from the response and I am not able to resolved the issue that I am getting.

Error: TypeError: Cannot read property 'get' of undefined

This error specifically occurs for the 4th line of component function.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • The value you return in the observable from `sendUserCredentials` is just `"logged-in"`, a string. Why *would* it have headers? Have you looked into the built-in request/response testing https://angular.io/guide/http#testing-http-requests? Also note that a component shouldn't really deal with details of the transport layer, like response headers, so that should be done in the service. – jonrsharpe Feb 20 '20 at 10:43
  • @jonrsharpe need a bit of advice that how to test a component function where we have consumed http service. Am I using the right way or there is something else has to be done in the unit test? – Shahzaib Imran Feb 20 '20 at 10:52
  • The docs I link above provide exactly that advice, how to test things that consume HTTP. But my point is the component shouldn't know about HTTP, that's one of the points of introducing the service. There's also more at https://angular.io/guide/testing. – jonrsharpe Feb 20 '20 at 10:54
  • @jonrsharpe I am not able to use the docs according to my code. Can you please write a solution for the above question? – Shahzaib Imran Feb 20 '20 at 10:55

0 Answers0