簡體   English   中英

沒有 HttpClient 的提供者! Angular測試

[英]No provider for HttpClient! Angular test

我在我的 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: No provider for 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)'),
    });
  }
  
}

將 HttpClientTestingModule 添加到您的測試設置應該可以解決問題:

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

從這里導入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM