【问题标题】:ERROR NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]: NullInjectorError: No provider for MatDialog错误 NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]: NullInjectorError: MatDialog 没有提供程序
【发布时间】:2021-08-06 13:43:20
【问题描述】:

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

在我的应用程序中,我创建了一个使用 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();
   });
});

Print of the error

【问题讨论】:

    标签: angular testing jasmine karma-runner


    【解决方案1】:

    你可以这样模拟它:

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

    【讨论】:

    • 我按照你说的做了,还是犯了同样的错误。
    • 您的 KDSDialogService 在导入数组中,而不是在提供者中。这是故意的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2021-03-06
    • 2018-03-24
    • 1970-01-01
    • 2022-07-24
    • 2019-06-22
    • 2020-11-30
    相关资源
    最近更新 更多