【问题标题】:Karma unit testing error: Unexpected value imported by the module. Please add a @NgModule annotationKarma 单元测试错误:模块导入了意外的值。请添加@NgModule 注释
【发布时间】:2023-03-12 11:51:01
【问题描述】:

我通过以下方式创建了一个全新的组件:

ng g mytest1

然后我将构造函数行改为:

constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }

,并添加了所需的导入:

import { MatDialogRef } from '@angular/material';

之后我通过以下方式运行 Karma 单元测试项目:

ng test

测试失败。我收到此错误消息:

错误:StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: 没有 MatDialogRef 的提供者!

为了解决这个问题,我在 beforeEach 部分添加了 Import 语句:

import { MatDialogRef } from '@angular/material';

//...

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ Mytest1Component ],
        imports: [MatDialogRef],
    })
    .compileComponents();
}));

现在我遇到了这个新错误,我无法修复:

失败:模块“DynamicTestModule”导入了意外的值“MatDialogRef”。请添加@NgModule 注解。

有人可以澄清我应该在哪里添加@NgModule 注释,或者我做错了什么吗?

谢谢。

【问题讨论】:

    标签: angular unit-testing electron karma-jasmine ng-modules


    【解决方案1】:

    你在组件中注入MatDialogRef:

    constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }
    

    因此,testBed 期望将与 provider 相同的内容注入到 TestBed。或者你也可以提供一个MockDialogueService给它。

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ Mytest1Component ],
            providers: [ MatDialogRef ],
        })
        .compileComponents();
    }));
    

    【讨论】:

    • 谢谢。那是我的第一个错误。现在我遇到了另一个问题,如果您能提供帮助,将不胜感激... 是说,“失败:无法解析 MatDialogRef 的所有参数:(?, ?, ?, ?)。”
    • 更新:我不得不听从这里的建议:stackoverflow.com/questions/48058457/…
    【解决方案2】:

    使用:

    imports: [MatDialogModule],
    

    改为

    【讨论】:

    • 谢谢。我仍然收到消息,“错误:StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!”
    • 更新:那行很有用。仍然缺少的是 nircraft 提出的建议:'providers: [ MatDialogRef ],' 谢谢你的帮助。
    猜你喜欢
    • 2021-10-07
    • 2017-10-23
    • 2020-12-27
    • 2022-01-22
    • 1970-01-01
    • 2018-01-10
    • 2018-05-24
    • 2019-12-01
    • 2021-09-02
    相关资源
    最近更新 更多