Вы предоставляете услугу только для одного теста, а именно первого. Блок beforeEach
находится внутри блока describe
. Это означает, что все блоки it
внутри блока describe
будут иметь доступ к предоставленной службе, но ни один снаружи.
Вот обновленная версия, которая должна работать.
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {AviorBackendService} from './avior-backend.service';
describe('AviorBackendService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AviorBackendService],
}));
it('should be created', () => {
const service: AviorBackendService = TestBed.get(AviorBackendService);
expect(service).toBeTruthy();
});
it('expects service to fetch data with proper sorting', () => {
const service: AviorBackendService = TestBed.get(AviorBackendService);
// tslint:disable-next-line: prefer-const
let httpMock: HttpTestingController;
service.getUserCollection().subscribe(data => {
expect(data.length).toBe(7);
const req = httpMock.expectOne('http://localhost:3000/users');
expect(req.request.method).toEqual('GET'); // Then we set the fake data to be returned by the mock
req.flush({firstname: 'Chad'});
});
});
it('should create the Preferences Service', inject([AviorBackendService], (service: AviorBackendService) => {
expect(service).toBeTruthy();
}));
});
Метод предоставленный блоку beforeEach
будет запускаться перед каждым блоком it
и инициализировать ваш TestBed сервисом, который ранее отсутствовал.