首页 > 解决方案 > 错误 NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]: NullInjectorError: MatDialog 没有提供程序

问题描述

我正在对我的应用程序进行单元测试。我是测试新手,所以我需要你的帮助。

在我的应用程序中,我创建了一个使用 MatDialog(KDSDialogService)的服务。我尝试将许多导入替代品、我的服务或 matdialog 作为提供者我不知道该怎么做

export declare class KDSDialogService {
    dialog: MatDialog;
    private dialogRef;
    constructor(dialog: MatDialog);
    open(componentOrTemplateRef: ComponentType<any> | TemplateRef<any>, title?: string, data?: any, size?: DialogSize, showClose?: boolean): MatDialogRef<any, any>;
    static ɵfac: ɵngcc0.ɵɵFactoryDef<KDSDialogService, never>;
}

在我的 home.component.spec 中,我在这里导入并声明,但我仍然收到此错误。

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

   beforeEach(async(() => {
      TestBed.configureTestingModule({
         declarations: [HomeComponent ],
         imports:[KDSDialogService, MatDialogModule],
  
      }).compileComponents();
   }));

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

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

打印错误

标签: angulartestingjasminekarma-runner

解决方案


你可以像这样模拟它:

import { MatDialog } from '@angular/material/dialog';
//...
    let matDialogService: jasmine.SpyObj<MatDialog>;
    matDialogService = jasmine.createSpyObj<MatDialog>('MatDialog', ['open']);

    TestBed.configureTestingModule({
      providers: [
        {
          provide: MatDialog,
          useValue: matDialogService,
        },


推荐阅读