没有 HttpClient 的提供者!角度测试

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

我在 ngmodel 数组中导入了 HTTP 客户端,但是当我运行测试时,我仍然得到 HttpClient 的 No provider!错误。我是否可能错过了测试本身的导入?

每个组件的每次测试都会给出此错误。即使只是简单地检查字符串是否相同。不知道我在这里做错了什么

我的 app.module 代码:

import { NgModule, isDevMode } from '@angular/core';
import { QuillModule } from 'ngx-quill';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './shared/nav/nav.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { FooterComponent } from './shared/footer/footer.component';
import { FormsModule } from "@angular/forms";
import { LoginComponent } from './pages/account/login/login.component';
import { RegistrationComponent } from './pages/account/registration/registration.component';
import { NotificationsComponent } from './pages/notifications/notifications.component';
import { HomepageComponent } from './pages/homepage/homepage.component';
import { PostComponent } from './partial/post/post.component';
import { LandingComponent } from './pages/landing/landing.component';
import { CreatePostMenuComponent } from './partial/create-post-menu/create-post-menu.component';
import { SettingsComponent } from './pages/settings/settings.component';
import { HttpClientModule } from '@angular/common/http';
import Quill from "quill";
import { QuillHandlers } from "./handlers/quill.handlers";
import { CommunityListComponent } from './pages/community/community-list/community-list.component';
import { CommunityCardComponent } from './partial/community-card/community-card.component';
import { CreateCommunityMenuComponent } from './partial/create-community-menu/create-community-menu.component';
import { ImageCropperModule } from 'ngx-image-cropper';


import { CommunityBannerComponent } from './partial/community-banner/community-banner.component';
import { CommunityDetailComponent } from './pages/community/community-detail/community-detail.component';
import { AccountDetailComponent } from './pages/account/account-detail/account-detail.component';

const FontAttributor = Quill.import('attributors/class/font');
FontAttributor.whitelist = [
  'Gotham',
];
Quill.register(FontAttributor, true);

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    FooterComponent,
    LoginComponent,
    NotificationsComponent,
    HomepageComponent,
    PostComponent,
    LandingComponent,
    CreatePostMenuComponent,
    SettingsComponent,
    RegistrationComponent,
    CommunityListComponent,
    CommunityCardComponent,
    CreateCommunityMenuComponent,
    CommunityDetailComponent,
    CommunityBannerComponent,
    AccountDetailComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: !isDevMode(),
      // Register the ServiceWorker as soon as the application is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000'
    }),
    QuillModule.forRoot({
      modules: {
        syntax: true,
        toolbar: [],
      },
      customOptions: [{
        import: 'formats/font',
        whitelist: ['Gotham'],
      }],
      suppressGlobalRegisterWarning: true,
    }),
    FormsModule,
    ImageCropperModule,
    HttpClientModule,
  ],
  providers: [
    QuillHandlers,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

我的测试代码:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { GenericService } from 'src/app/services/API/generic.service';
import { CommunityDetailComponent } from './community-detail.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClientModule } from '@angular/common/http';
 
describe('CommunityDetailComponent', () => {
  let component: CommunityDetailComponent;
  let fixture: ComponentFixture<CommunityDetailComponent>;
  const testString = "test";
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, HttpClientTestingModule ],
      declarations: [ CommunityDetailComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CommunityDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('tester', () => {
    expect("test").toBe(testString)
  });
});

具体错误: NullInjectorError:R3InjectorError(DynamicTestModule)[ActivatedRoute -> ActivatedRoute]: NullInjectorError:没有ActivatedRoute的提供者!

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';

import { EnrollmentService } from 'src/app/services/API/enrollment.service';
import { CommonService } from 'src/app/services/common.service';
import { SweetAlert } from '../../../helpers/sweetalert.service';
import { Community } from '../../../models/domain/Community';
import { CommunityService } from '../../../services/API/community.service';




@Component({
  selector: 'app-community-detail',
  templateUrl: './community-detail.component.html',
  styleUrls: ['./community-detail.component.scss']
})
export class CommunityDetailComponent {
  community!: Community;
  subscription!: Subscription;
  communityId!: string | null;
  dataLoaded: boolean = false;


  constructor(private communityService: CommunityService, private enrollmentService: EnrollmentService, private route: ActivatedRoute, private router: Router, private commonService : CommonService) {

  }
  ngOnInit(): void {
    this.route.paramMap.subscribe((params) => {
      this.communityId = params.get('id');
      if (this.communityId) {
        console.log("community detail got param community id:" + this.communityId)
        this.getCommunity();
      } else {
        SweetAlert.showErrorAlert("Kan geen community geven met het opgegeven id.")
        this.router.navigateByUrl('community');
      }
    });
    this.commonService.getUpdate().subscribe((data) => {
      this.getCommunity();
    });
  }


  //api cal to enroll the currently logged in user for the community
  //0 represents the role 'MEMBER'
  joinCommunity(): void {
    this.subscription = this.enrollmentService.enroll(this.communityId!, 2).subscribe({
      next: (v) => {
        SweetAlert.showSuccessAlert("Je bent nu lid van deze community!")
        console.log(v)
      },
      error: () => SweetAlert.showErrorAlert("Er is iets misgegaan, je bent mogelijk al lid van deze community."),
      complete: () => console.log('joining community complete (ui)'),
    });
  }


  //api call to get the community with the id from the route params.
  private getCommunity() {
    console.log("get community called")
    this.subscription = this.communityService.get(this.communityId!).subscribe({
      next: (v) => {
        console.log(v);
        this.community = v;
      },
      error: (e) => console.log("Error when Getting community"),
      complete: () => console.log('getting community complete (ui)'),
    });
  }
  
}

angular http testing
2个回答
3
投票

将 HttpClientTestingModule 添加到测试设置中应该可以解决问题:

TestBed.configureTestingModule({
  imports: [HttpClientTestingModule, ...],
  ..
}).compileComponents();

从这里导入:

import { HttpClientTestingModule } from '@angular/common/http/testing';

0
投票

错误问题错误 cuando ejecuto ng 测试:NullInjectorError:R3InjectorError(HowworkService - > HowworkService - > HttpClient - > HttpClient): NullInjectorError:没有 HttpClient 的提供者!

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { HowworkService } from './howwork.service';

describe('HowworkService', () => {
  let service: HowworkService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule] 
    });
    service = TestBed.inject(HowworkService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

¿Cómo prodría solucionarlo?

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