测试中未定义服务中的注入服务

时间:2019-10-16 09:40:24

标签: angular angular-test angular-testing

我使用ServiceLocator.injector在构造函数中注入了服务。当我运行单元测试时,它显示错误“ TypeError:无法读取未定义的'environmentWeb'”。 environmentWeb()是我在构造函数中注入的服务的一种方法。

我尝试将Service放入提供程序中,并尝试使用TestBed.get(Service)将Service注入测试用例中,但是没有用

ReportService.ts

export class ReportService extends ReportsCommonDataObject {
    private dataLoaded: boolean = false;
    protected http: HttpClient;
    protected performanceService: PerformanceService;
    protected performanceSecondLevelService: PerformanceSecondLevelService;
    protected sharedService: SharedService;
    protected utilService: UtilService;
    constructor() {
        super();

        setTimeout(() => {
            this.performanceService = ServiceLocator.injector.get<PerformanceService>(PerformanceService);
            this.performanceSecondLevelService = ServiceLocator.injector.get<PerformanceSecondLevelService>(PerformanceSecondLevelService);
            this.sharedService = ServiceLocator.injector.get<SharedService>(SharedService);
            this.utilService = ServiceLocator.injector.get<UtilService>(UtilService);
            this.http = ServiceLocator.injector.get<HttpClient>(HttpClient);     
        });
    }

report.service.spec.ts:

describe('ReportService', () => {

    let reportService: ReportService;
    let httpTestingController: HttpTestingController;    
    let sharedService: SharedService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                SharedService,
                HttpClient,
                ReportService,
                PerformanceService,
                PerformanceSecondLevelService,
                MatDialog,
            ],
            imports: [
                AppModule,
                BrowserModule,
                HttpClientTestingModule
            ],
        }).compileComponents()

        // Inject the http service and test controller for each test
        httpTestingController = TestBed.get(HttpTestingController);
        reportService = TestBed.get(ReportService);
        sharedService = TestBed.get(SharedService);

    });

1 个答案:

答案 0 :(得分:0)

代替:

reportService = TestBed.get(ReportService);\
sharedService = TestBed.get(SharedService);

试试这个:

reportService = new ReportService();\
sharedService = new SharedService();