Cannot get MockBackend to return an error response

I have an issue when I try to unit test using the Angular 2 MockBackend

My tests for backend success responses works fine, but when I try to mock an error response from the backend, it always goes in the success case.

I bind the following to two different buttons where one passes true and the other passes false to the function. No matter what button i press we always get to the success block in the subscribtion. What am I missing?

callHttp(success) {
  let connection;
  mockBackend.connections.subscribe(c => connection = c);
  this.http.get("/test")
    .subscribe(
      res => {
        let msg = "Success status ("+res.status+")";
        console.log(msg);
        this.latestMessage = msg;
      }),
      err => {
        // We never get here...
        let msg = "Error status ("+res.status+")";
        console.log(msg);
        this.latestMessage = msg;
      });
  connection.mockRespond(new Response(new BaseResponseOptions().merge({
    status: success ? 200 : 401,
    body: JSON.stringify("Response")
  })));
}

I have reproduced the issue in the following plunk: http://plnkr.co/edit/Rsl8Zcj6iEAIoD8KDDly

When I run the code with the actual backend, it works as expected. My problem is merely to mock the error responses, when I write tests.

Upvotes: 3

Views: 1124

Answers (1)

The MockConnection object has a mockError(err?: Error) function, which you should call instead of mockRespond.

Upvotes: 8

Related Questions