我在这里有测试代码:
import { TestBed, inject } from '@angular/core/testing';
import { AviorBackendService } from './avior-backend.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
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();
}));
您可以看到提供了AviorBackendService,但是对于第二个和第三个测试,仍然抛出该错误。如何解决呢?我尝试将其更改为声明,但这给了我其他新的错误,因此这似乎不是适当的解决方案。
您只为单个测试(即第一个测试)提供服务。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。