2

I want to test this function:

register(): void {
  let user: User = new User();
  user.username = this.username.value;
  user.email = this.email.value;
  user.password = this.password.value;
  this._authService.register(user)
    .map(rsp => rsp.json())
    .subscribe((response) => { // 
      this._router.parent.navigate(["Login"]); // 
    }, (error) => {
      this.responseError = JSON.parse(error._body).message; 
    }, () => {
      this._authService.login(user)
        .map(rsp => rsp.json())
        .subscribe((data: any) => { // 
          this._authService.handleSuccessLogin(data, user);
          this._router.parent.navigate(["../Game"]);
        });
    });
  }

My _authService using http but I want to fake that call. I have tried to call through in it and mocking the http, but even if my response was 4xx it ran on the success part. Is it possible to test the error part somehow?

1 Answer 1

2

To simulate an error, you need to use the mockError method of the MockConnection. It accepts an Error object as parameter not a Response one. To be able to provide hints like status code, you could extend the Error class like that:

class ResponseError extends Error {
  status: number;
  (...)
}

and use it this way:

it('Should return something', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
  mockBackend.connections.subscribe(
    (connection: MockConnection) => {
      if (connection.request.url === 'file1.json') {
        var err = new ResponseError();
        err.status = 404;
        connection.mockError(err);
        (...)

In this case, an error is thrown in your data flow and gotten for example into the second callback specified in the subcribe method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.