首页 > 解决方案 > 我的 Karma-Jasmine 单元测试用例缺少什么?

问题描述

我试图在我的代码库中修复一些测试用例,并发现了这个我似乎无法弄清楚的特殊情况。

测试运行但它抱怨NullInjectorError: No provider for Function!

我无法弄清楚为什么我会收到此错误消息。

角度版本:11.2.10

这是测试用例(没有什么不寻常的) - 包括所有导入(但为简洁起见,此处省略):

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

import { BLADE_DATA, BladeComponent } from './blade.component';
import { RouterTestingModule } from '@angular/router/testing';
import { PortalModule } from '@angular/cdk/portal';

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

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [BladeComponent],
      imports: [RouterTestingModule, PortalModule ],
    }).compileComponents();
  }));

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

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

这是组件 - 也是非常基本的:

@Component({
  selector: 'app-blade',
  templateUrl: './blade.component.html',
  styleUrls: ['./blade.component.scss'],
})
export class BladeComponent {

  public title: string;
  public parentTab: TabInfo;
  public showOpenTabIcon = true;

  constructor(public component: Type<any>) {}

  /**
   * Convenience function to set this base class data from the injected data object.
   *
   * @param data the data for this blade
   */
  protected setData(data: any): void {
    // ...
    // sets the data (i.e. this.title = data.title)
  }
}

这是错误消息:

NullInjectorError: R3InjectorError(DynamicTestModule)[Function -> Function]: 
  NullInjectorError: No provider for Function!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'Function', 'Function' ] })
    at <Jasmine>
    at NullInjector.get (node_modules/@angular/core/fesm2015/core.js:11102:1)
    at R3Injector.get (node_modules/@angular/core/fesm2015/core.js:11269:1)
    at R3Injector.get (node_modules/@angular/core/fesm2015/core.js:11269:1)
    at NgModuleRef$1.get (node_modules/@angular/core/fesm2015/core.js:25299:1)
    at Object.get (node_modules/@angular/core/fesm2015/core.js:25013:1)
    at lookupTokenUsingModuleInjector (node_modules/@angular/core/fesm2015/core.js:3389:1)
    at getOrCreateInjectable (node_modules/@angular/core/fesm2015/core.js:3501:1)
    at ɵɵdirectiveInject (node_modules/@angular/core/fesm2015/core.js:14693:1)
    at NodeInjectorFactory.BladeComponent_Factory [as factory] (ng:///BladeComponent/ɵfac.js:4:42)
    at getNodeInjectable (node_modules/@angular/core/fesm2015/core.js:3596:1)
Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (src/app/navigation/blade/blade.component.spec.ts:26:23)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:292:1)

标签: angularunit-testingkarma-jasmine

解决方案


推荐阅读