Angular 5 (Karma / Jasmine Testing) - Using a mock

2019-08-23 15:20发布

I don't quite understand how the MockBackend feature works as described over here. I am completely new to Angular.

I want to program some test cases to make sure that when a server error occurs in the backend, the Angular components I have do display error messages on the frontend. That requires having HTTP requests that return errors on purpose. I am running into trouble with the jasmine-ajax and the nock packages, but someone told me about programming an instance

Even if you have an actual backend already implemented, can you still create a mock backend to test appearance of form messages which do require HTTP requests first before they are displayed?

One example is when the user is asked to fill out a sales form, and upon sending it over, the server encounters an error and sends a 500 Internal Server Error response back, which the frontend then displays a server error message.

I don't quite understand mock backends in Angular. My worry is that by having a mock backend, it will cause all the requests I'm making in the controllers of the components, as well as the requests made in the test cases, be issued to the mock backend instead of the actual backend, thereby introducing false-positive fails in my test suite.

If I program my test suite to use the MockBackend class from '@angular/http/testing', will this cause my HTTP requests on all the Angular components to be issued to that mock backend server instead of the actual server?

EDIT: This is a case of what I'm referring to. By using MockBackend, some of the tests that require sending HTTP requests to the actual server will not be sent.

2条回答
Explosion°爆炸
2楼-- · 2019-08-23 15:55

Correct me if I'm wrong, judging by your description I assume you're using http module. You could consider upgrading to the httpClient module, for which testing against server errors is pretty straightforward: https://angular.io/guide/http#testing-for-errors

By the way unit tests should be self contained. You should mock all the dependencies (probably providers for your testing module) and not send any requests to the actual server. Both information and status codes can be mocked using http testing module.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-23 16:03

I consider mocking httpclient to be a code smell. I prefer creating my own api classes that wrap http or httpClient. Then in your unit tests you can use a jasmin spy to return data you need for your tests.

see this example https://angular.io/guide/http

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}

configUrl = 'assets/config.json';

getConfig() {
  return this.http.get(this.configUrl);
}

then in your tests (pseudo code, don't remember the syntax):

spyOn(configService, 'getConfig').and.returnValues({data:123});
查看更多
登录 后发表回答