Angular Karma Jasmine - 没有 LocaleService 的提供者

标签 angular karma-jasmine karma-coverage

当我尝试使用 karma jasmin 进行测试时,出现此错误...

NullInjectorError: StaticInjectorError(DynamicTestModule)[DaterangepickerDirective -> LocaleService]: 
  StaticInjectorError(Platform: core)[DaterangepickerDirective -> LocaleService]: 
    NullInjectorError: No provider for LocaleService!

我的组件

import { Component, OnInit } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ApiService } from '../../../services/api.service';
import * as moment from 'moment';

@Component({
  selector: 'ngx-item-analytics',
  templateUrl: './item-analytics.component.html',
  styleUrls: ['./item-analytics.component.scss']
})
export class ItemAnalyticsComponent implements OnInit {

  data: any;
  data2: any;
  showBarchart1: boolean = false;
  showBarchart2: boolean = false;
  maxDate: moment.Moment;
  minDate: moment.Moment;
  datepickerChanges:boolean = false;
  dateGrouped:Date;
  alwaysShowCalendars: boolean;
  keepCalendarOpeningWithRange: boolean;
  showRangeLabelOnInput: boolean;
  invalidDates: moment.Moment[] = [];
  selected: any;
  startDate:any;
  endDate:any;
  datagroupedChart:boolean=false;
  datagrouped:any[] =[];
  venues: any = [];
  selectedVenue: any = 'Oahu';
  selVenue: any;

  ranges: any = {
    Today: [moment(), moment()],
    Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
    'This Month': [moment().startOf('month'), moment().endOf('month')],
    'Last Month': [
      moment()
        .subtract(1, 'month')
        .startOf('month'),
      moment()
        .subtract(1, 'month')
        .endOf('month')
    ],
    'Last 3 Month': [
      moment()
        .subtract(3, 'month')
        .startOf('month'),
      moment()
        .subtract(1, 'month')
        .endOf('month')
    ]
  };

  isInvalidDate = (m: moment.Moment) =>  {
    return this.invalidDates.some(d => d.isSame(m, 'day') );
  }
  timezone: any;
  constructor(private spinner: NgxSpinnerService,
              private apiService: ApiService,) {
              this.datagrouped = [{"State":"CA","Under 5 Years":2704659,"5 to 13 Years":4499890,"14 to 17 Years":2159981,"18 to 24 Years":3853788,"25 to 44 Years":10604510,"45 to 64 Years":8819342,"65 Years and Over":4114496},{"State":"TX","Under 5 Years":2027307,"5 to 13 Years":3277946,"14 to 17 Years":1420518,"18 to 24 Years":2454721,"25 to 44 Years":7017731,"45 to 64 Years":5656528,"65 Years and Over":2472223},{"State":"NY","Under 5 Years":1208495,"5 to 13 Years":2141490,"14 to 17 Years":1058031,"18 to 24 Years":1999120,"25 to 44 Years":5355235,"45 to 64 Years":5120254,"65 Years and Over":2607672},{"State":"FL","Under 5 Years":1140516,"5 to 13 Years":1938695,"14 to 17 Years":925060,"18 to 24 Years":1607297,"25 to 44 Years":4782119,"45 to 64 Years":4746856,"65 Years and Over":3187797},{"State":"IL","Under 5 Years":894368,"5 to 13 Years":1558919,"14 to 17 Years":725973,"18 to 24 Years":1311479,"25 to 44 Years":3596343,"45 to 64 Years":3239173,"65 Years and Over":1575308},{"State":"PA","Under 5 Years":737462,"5 to 13 Years":1345341,"14 to 17 Years":679201,"18 to 24 Years":1203944,"25 to 44 Years":3157759,"45 to 64 Years":3414001,"65 Years and Over":1910571}];
              this.maxDate = moment().add(0,  'weeks');
              this.minDate = moment().subtract(3, 'days');
              this.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
              this.alwaysShowCalendars = true;
              this.keepCalendarOpeningWithRange = true;
              this.showRangeLabelOnInput = true;
              this.dateGrouped = new Date()
              this.selected = {startDate: moment().subtract(30, 'days'), endDate: moment()};
              setTimeout(() => {
                this.invalidDates = [moment().add(2, 'days'), moment().add(3, 'days'), moment().add(5, 'days')];
              }, 5000);
              var m = moment(this.selected.startDate);
                     m.set({hour:0,minute:0,second:0,millisecond:0})
             this.startDate = m.format('YYYY-MM-DD 00:00');
             this.endDate = moment(this.selected.endDate).format('YYYY-MM-DD 23:59');



               }
  rangeClicked(range) { }
  datesUpdated(range) {
    var m = moment(this.selected.startDate);
            m.set({hour:0,minute:0,second:0,millisecond:0})
    this.startDate = m.format('YYYY-MM-DD 00:00');
    this.endDate = moment(this.selected.endDate).format('YYYY-MM-DD 23:59');
    this.viaAirportAnalytics();
  }
              
  viaAirportAnalytics(){
    var statrdate = new Date(this.startDate).toISOString();
    var endDate = new Date(this.endDate).toISOString();
                           
    this.spinner.show();
    this.apiService.getVenues().subscribe((res)=>{
      this.spinner.hide();
      this.venues = res.body.venues;
      this.selVenue = this.venues[0];
      
    for(let sel of this.venues){
      if(sel.name == this.selectedVenue) {
        this.selVenue = sel;
      }
    }
    let arg = {
      startDate:statrdate,
      endDate:endDate,
      venueId:this.selVenue._id
    }
    this.spinner.show();
    this.apiService.getItemAnalyticsItemCategory(arg).subscribe((res)=>{
      this.spinner.hide();
      let dataChart = [];
      res.chartData.map(data =>{
        dataChart.push(
          {gate:data.category, deliveries: data.count})
      })
      
      if(dataChart.length>0){
        this.showBarchart1 = true;
        this.data = dataChart;
      } else {
        this.showBarchart1 = false;
      }
    });
    
    this.spinner.show();
    this.apiService.getItemAnalyticsItems(arg).subscribe((res)=>{
      this.spinner.hide();
      let dataChart = [];
      res.chartData.map(data =>{
        dataChart.push(
          {gate:data.menuItem, deliveries: data.count})
      })
      
      if(dataChart.length>0){
        this.showBarchart2 = true;
        this.data2 = dataChart;
      } else {
        this.showBarchart2 = false;
      }
    });
    });
    
  }
  onDateSelect(event){
    var m = moment(event);
    m.set({hour:0,minute:0,second:0,millisecond:0})
    var r = moment(event);
    r.set({hour:23,minute:59,second:59,millisecond:59})
    this.startDate = m.format('YYYY-MM-DD 00:00');
    this.endDate = r.format('YYYY-MM-DD 23:59');
      }
  ngOnInit() { }

}

规范.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { StoreAnalyticsComponent } from './store-analytics.component';
import { NbCardModule, NbDatepickerModule } from '@nebular/theme';
import { FormsModule } from '@angular/forms';
import { ChartModule } from 'angular2-chartjs';
import { NgxDaterangepickerMd, LocaleService } from 'ngx-daterangepicker-material';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpClient, HttpHandler } from '@angular/common/http';



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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: 
      [
        NbCardModule,
        FormsModule,
        NbDatepickerModule,
        NgxDaterangepickerMd,
        ChartModule,

      ],
      providers:[
        HttpClient,
        HttpHandler,
        
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
     
      declarations: [ StoreAnalyticsComponent ]
    })
    .compileComponents();
  }));

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

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

组件 2

组件


import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../../../services/api.service';
import { NgxSpinnerService } from "ngx-spinner";

@Component({
  selector: 'ngx-order-confirmation',
  templateUrl: './order-confirmation.component.html',
  styleUrls: ['./order-confirmation.component.scss']
})
export class OrderConfirmationComponent implements OnInit {
  
  cartId:any;
  recipientDetails:any;
  subscriptionId:any;

  interval;
  timeLeft: number = 20;

  constructor(public router: Router,public ApiService: ApiService, private spinner: NgxSpinnerService) { 
    this.spinner.show();
    this.recipientDetails  = JSON.parse(localStorage.getItem('recipientDetails')) || {};
   
    this.subscriptionDetail();
  }

  ngOnInit() {
 
  }

  subscriptionDetail(){
    this.ApiService.subscriptionDetails(this.recipientDetails.recipientAddressesId).subscribe((res)=>{
      if(res && res.body && res.body.subscriptionDetails && res.body.subscriptionDetails[0]){
        this.subscriptionId = res.body.subscriptionDetails[0].subscriptionId;
        this.spinner.hide();
      } else {
        setTimeout(()=>{ 
          this.subscriptionDetail();
        }, 2000);
      }
     });
  }
}

规范.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { OrderConfirmationComponent } from './order-confirmation.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ OrderConfirmationComponent ],
      imports: [RouterTestingModule,HttpClientTestingModule],
    })
    .compileComponents();
  }));

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

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

谢谢...................................... ..................................................... ..................................................... ..................................................... ..................................................... ...

最佳答案

NgxDaterangepickerMd.forRoot() 应该提供所有必需的服务以及 LocaleService

TestBed.configureTestingModule({
  imports: [      [
    ...
    NgxDaterangepickerMd.forRoot(),

关于Angular Karma Jasmine - 没有 LocaleService 的提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63204570/

相关文章:

Angular 错误 - 通用类型 'ModuleWithProviders<T>' 需要 1 个类型参数

angular - 使用 REST API 时 mat-table 数据源不起作用

javascript - sinon server.autoRespond

javascript - Karma 无法读取未定义的 socket.io 的属性 'prototype'?

sapui5 - 即使未满足测试覆盖率阈值, karma 覆盖退出代码始终为 0

angular - 如何让我的 ngx-line-chart 响应?

Angular 2 降级组件 : Why the constructor params bring this error: (SystemJS) Can't resolve all parameters for (? )

Angular 4 测试 - [object ErrorEvent] 抛出

ember-cli - 如何修复 Ember testem 中出现 'could not load' 、 'failed' 、 'could not find module' 或 'died' 等错误的测试?

Angular(ng 测试)调试 - VS 代码不会在断点处停止