$httpBackend in modern Angular
$httpBackend becomes HttpTestingController, enabled with provideHttpClientTesting. The test makes the call first and then answers the captured request.
Before · AngularJS
it('loads users', function () {
$httpBackend.expectGET('/api/users').respond([{ id: 1 }]);
var users;
UserService.getAll().then(function (res) { users = res.data; });
$httpBackend.flush();
expect(users.length).toBe(1);
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});After · AngularbeforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
it('loads users', () => {
let users: User[] = [];
TestBed.inject(UserService).getAll().subscribe(res => (users = res));
const req = http.expectOne('/api/users');
expect(req.request.method).toBe('GET');
req.flush([{ id: 1 }]);
expect(users.length).toBe(1);
});
afterEach(() => http.verify());What changes
- The order is reversed: call the service, then use expectOne to get the pending request and assert on it.
- Each request is answered on its own with req.flush(body); pass a status and statusText as the second argument to simulate an error.
- http.verify() replaces verifyNoOutstandingExpectation and verifyNoOutstandingRequest.
Migration tip. List provideHttpClient() before provideHttpClientTesting(), or the testing backend will not be used. Apps that used ngMockE2E to fake the whole API in the browser need a different tool for that, such as an interceptor or a mock server.
Related
- Protractor
- $interpolateProvider / $interpolate
- ng-pluralize
- ngMock unit tests (module, inject, $controller)
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn