【问题标题】:unit test fail with NullInjectorError in AngularAngular 中的单元测试因 NullInjectorError 而失败
【发布时间】:2021-11-26 22:45:32
【问题描述】:

我已经配置了 jest 框架的单元测试并且还移除了 jasmine karma(默认单元测试)

所以我们需要模拟任何东西还是我在导入中遗漏了一些东西?

下面我提到了测试代码

toolbar.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ToolbarComponent } from './toolbar.component';
import { ColorPickerModule } from 'ngx-color-picker';
import { NgxImageZoomModule } from 'ngx-image-zoom';
import { UiSwitchModule } from 'ngx-toggle-switch';
import { SharepointService } from '../../services/sharepoint.service';
import { CommonService } from '../../services/common.service';
import { InjectionToken } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

export const BASE_URL = new InjectionToken<string>('BASE_URL');

describe('ToolbarComponent', () => {
  let component: ToolbarComponent;
  let fixture: ComponentFixture<ToolbarComponent>;
  let sharepointService: SharepointService;
  let commonService: CommonService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ColorPickerModule,
        NgxImageZoomModule,
        UiSwitchModule,
        HttpClientTestingModule],
      declarations: [ToolbarComponent],
      providers: [{ provide: ToolbarComponent, useValue: "test" },
        SharepointService,
        CommonService,
        HttpClient]
    })
      .compileComponents();
  }));

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

    sharepointService = TestBed.inject<SharepointService>(SharepointService);
    commonService = TestBed.inject<CommonService>(CommonService);
  });

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

抛出了一个错误:

NullInjectorError: StaticInjectorError(DynamicTestModule)[adalConfig]:
StaticInjectorError(Platform: core)[adalConfig]:
NullInjectorError: No provider for adalConfig!

Here I attached the test result screenshot

谢谢

【问题讨论】:

    标签: angular unit-testing jestjs


    【解决方案1】:

    如果您在组件中使用 adalConfig 服务,则在 .specs 数组中提供它

      providers: [{ provide: ToolbarComponent, useValue: "test" },
            SharepointService,
            CommonService,
            HttpClient,
            adalConfig
    ]
    

    或者如果是模块,那么在 imports:[] 数组中

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2014-04-09
      • 2014-06-14
      相关资源
      最近更新 更多