错误 NullInjectorError:R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]:NullInjectorError:没有 MatDialog 的提供程序

sou*_*ato 2 testing jasmine karma-runner angular

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

\n

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

\n
export declare class KDSDialogService {\n    dialog: MatDialog;\n    private dialogRef;\n    constructor(dialog: MatDialog);\n    open(componentOrTemplateRef: ComponentType<any> | TemplateRef<any>, title?: string, data?: any, size?: DialogSize, showClose?: boolean): MatDialogRef<any, any>;\n    static \xc9\xb5fac: \xc9\xb5ngcc0.\xc9\xb5\xc9\xb5FactoryDef<KDSDialogService, never>;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
describe(\'HomeComponent\', () => {\n   let component: HomeComponent;\n   let fixture: ComponentFixture<HomeComponent>;\n\n   beforeEach(async(() => {\n      TestBed.configureTestingModule({\n         declarations: [HomeComponent ],\n         imports:[KDSDialogService, MatDialogModule],\n  \n      }).compileComponents();\n   }));\n\n   beforeEach(() => {\n      fixture = TestBed.createComponent(HomeComponent);\n      component = fixture.componentInstance;\n    \n   });\n\n   it(\'should create\', () => {\n      fixture.detectChanges();\n      expect(component).toBeTruthy();\n   });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

打印错误信息

\n

eko*_*eko 5

你可以这样嘲笑它:

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

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

Run Code Online (Sandbox Code Playgroud)