简体   繁体   English

为什么我收到这个错误:NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService?

[英]Why I'm getting this error : NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService?

I'm taking a course about angular testing and I trying to setup a test for a componet with a service and this service has the httpClias as depedency but I got this error when I tried to run it我正在学习一门关于角度测试的课程,我尝试为具有服务的组件设置测试,并且该服务将 httpClias 作为依赖项,但是当我尝试运行它时出现此错误

NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService -> HttpClient -> HttpClient]:
          NullInjectorError: No provider for HttpClient!
        error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'MedicoService', 'HttpClient', 'HttpClient' ] })
        NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService -> HttpClient -> HttpClient]:
          NullInjectorError: No provider for HttpClient!
            at NullInjector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10756:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10923:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10923:1)
            at injectInjectorOnly (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2290:1)
            at ɵɵinject (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2294:1)
            at Object.MedicoService_Factory [as factory] (ng:///MedicoService/ɵfac.js:5:41)
            at R3Injector.hydrate (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11091:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10912:1)
            at NgModuleRef$1.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24988:1)
            at TestBedRender3.inject (node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:1943:1)
        Error: Expected undefined to be truthy.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/intemedio2/medico/service/medico.service.spec.ts:14:21)
            at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:364:1)
            at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:292:1)
Chrome 86.0.4240.198 (Windows 10): Executed 1 of 28 (1 FAILED) (0 secs / 0.119 secs)
Chrome 86.0.4240.198 (Windows 10) MedicoService should be created FAILED
        NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService -> HttpClient -> HttpClient]:
          NullInjectorError: No provider for HttpClient!
        error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'MedicoService', 'HttpClient', 'HttpClient' ] })
        NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService -> HttpClient -> HttpClient]:
          NullInjectorError: No provider for HttpClient!
            at NullInjector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10756:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10923:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10923:1)
            at injectInjectorOnly (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2290:1)
            at ɵɵinject (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2294:1)
            at Object.MedicoService_Factory [as factory] (ng:///MedicoService/ɵfac.js:5:41)
            at R3Injector.hydrate (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11091:1)
            at R3Injector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10912:1)
            at NgModuleRef$1.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24988:1)
            at TestBedRender3.inject (node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:1943:1)
        Error: Expected undefined to be truthy.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/intemedio2/medico/service/medico.service.spec.ts:14:21)
            at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:364:1)
Chrome 86.0.4240.198 (Windows 10): Executed 26 of 28 (1 FAILED) (skipped 2) (0.382 secs / 0.316 secs)

All thaI have is this service (medicosService)我所拥有的就是这项服务 (medicosService)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MedicoService {

  constructor(public http: HttpClient) { }



  getMedicos() {

    return this.http.get('....');
  }
}

and this component和这个组件

import { MedicoService } from './service/medico.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-medico',
  templateUrl: './medico.component.html',
  styleUrls: ['./medico.component.css']
})
export class MedicoComponent implements OnInit {

  constructor(public medicoService: MedicoService) { }

  medicos: any [] = []
  ngOnInit(): void {
  }

  saludarMEdico(nombre: string): string {
    return `hello ${nombre}`;
  }


  optenerMedicos() {
    this.medicoService.getMedicos().subscribe((medicos: any []) => {
      this.medicos = medicos;
    })
  }
}

and this is the test这是测试

import { MedicoService } from './service/medico.service';
import { ComponentFixture, TestBed } from '@angular/core/testing';
/** El testbed es una clase con muchos metodos  para hacewr pruebas */
import { MedicoComponent } from './medico.component';
import { HttpClientModule } from '@angular/common/http';


describe('MedicoComponent', () => {
  let component: MedicoComponent;
  let fixture: ComponentFixture<MedicoComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MedicoComponent],
      providers: [MedicoService],
      imports:[HttpClientModule]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MedicoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  //comprueba que el componente se cree
  it('should create', () => {
    expect(component).toBeTruthy();
  });
// verificacion alternativa si el componente se creo, tenemos acceso a sus metodos
  it('should return a greeting based on the sent name', () => {
    const name = 'Gerardo';
    const greeting = component.saludarMEdico(name);
    expect(greeting).toContain(name);
  });

});

} }

I've tried to use HttpClientTestingModule instead of HttpClientModule in the imports but I have the same error so, I dont know what is going on.我试图在导入中使用 HttpClientTestingModule 而不是 HttpClientModule 但我有同样的错误,所以我不知道发生了什么。

The error comes from your service test medico.service.spec.ts not from your component test.错误来自您的服务测试medico.service.spec.ts而不是来自您的组件测试。

Try for example this in your service test:例如,在您的服务测试中尝试以下操作:

describe('YourService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule]
  }));

  it('should be created', () => {
    const service: YourService = TestBed.get(YourService);
    expect(service).toBeTruthy();
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我收到 NullInjectorError: R3InjectorError(DynamicTestModule)[MdbModalRef -&gt; MdbModalRef]:? - Why am i getting NullInjectorError: R3InjectorError(DynamicTestModule)[MdbModalRef -> MdbModalRef]:? NullInjectorError:R3InjectorError(DynamicTestModule)[FormBuilder -&gt; FormBuilder]:NullInjectorError:没有FormBuilder的提供者 - NullInjectorError: R3InjectorError(DynamicTestModule)[FormBuilder -> FormBuilder]: NullInjectorError: No provider for FormBuilder R3InjectorError(DynamicTestModule)[Store -&gt; Store]: NullInjectorError: No provider for Store - R3InjectorError(DynamicTestModule)[Store -> Store]: NullInjectorError: No provider for Store 错误 NullInjectorError:R3InjectorError(AppModule) - ERROR NullInjectorError: R3InjectorError(AppModule) Angular 8 使用 Karma 和 Jasmine 进行测试 NullInjectorError: R3InjectorError(DynamicTestModule)[api -&gt; api]: NullInjectorError: No provider for Z8A5DA52ED126447D359E7 - Angular 8 Testing with Karma and Jasmine NullInjectorError: R3InjectorError(DynamicTestModule)[api -> api]: NullInjectorError: No provider for api NullInjectorError: R3InjectorError(DynamicTestModule)[ApiService -&gt; HttpClient -&gt; HttpClient]: NullInjectorError: 没有 HttpClient 的提供者 - NullInjectorError: R3InjectorError(DynamicTestModule)[ApiService -> HttpClient -> HttpClient]: NullInjectorError: No provider for HttpClient NullInjectorError: R3InjectorError(DynamicTestModule)[Router -&gt; Function -&gt; Function]: NullInjectorError: No provider for Function - NullInjectorError: R3InjectorError(DynamicTestModule)[Router -> Function -> Function]: NullInjectorError: No provider for Function 错误:NullInjectorError:R3InjectorError(AuthorModule)[ScrollbarHelper -&gt; ScrollbarHelper -&gt; ScrollbarHelper -&gt; ScrollbarHelper]: - Error: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]: 错误 NullInjectorError:R3InjectorError(AppModule)[MessageService -&gt; MessageService -&gt; MessageService]: - ERROR NullInjectorError: R3InjectorError(AppModule)[MessageService -> MessageService -> MessageService]: 错误:未捕获(承诺):NullInjectorError:R3InjectorError(AppModule)[baseURL] - Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[baseURL]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM