NullInjectorError:StaticInjectorError [AviorBackendService]:NullInjectorError:即使提供了服务,也没有提供程序

问题描述 投票:0回答:1

我在这里有测试代码:

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,但是对于第二个和第三个测试,仍然抛出该错误。如何解决呢?我尝试将其更改为声明,但这给了我其他新的错误,因此这似乎不是适当的解决方案。

angular unit-testing karma-jasmine
1个回答
1
投票

您只为单个测试(即第一个测试)提供服务。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。

© www.soinside.com 2019 - 2024. All rights reserved.