我有一个指令,其中我通过inject关键字获取组件实例,如下所示:

export class MyDirective implements AfterViewInit {
  private component: MyBaseComponent = inject(MyBaseComponent);
  ...
}

MyBaseComponent是一个抽象组件,从中派生出多个其他控件(例如MyTextComponent).
MyDirective在组件的html—template中的用法示例:

<my-text-component my-directive>

所以'MyDirective'类中的'component'属性变成了'my—text—component'.

问题是,虽然单位测试与Jest .
单元测试的空框架代码如下所示:

describe("MyDirectiveTest", () => {
  let directive: MyDirective;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyDirective, MyBaseComponent, MyTextComponent],
      providers: [{ provide: MyBaseComponent, useClass: MyTextComponent }],
    });
    directive = new MyDirective();
  });

  it("should initialize correctly", () => {
    expect(directive).toBeTruthy();
  });
});

我得到了以下错误:

NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with 100.

它准确地显示了代码行,其中inject()是错误的来源.

PS:
在建议将@ injection()decorator 添加到MyDirective之前,
我已经试过了,除了指令和组件是注射默认无论如何.

推荐答案

你需要创建一个组件/使用一个现有组件来测试一个指令,一个指令不能单独初始化,这就是为什么你会得到这个错误,而是使用TestBed.createComponent(MyTextComponent)来初始化组件并通过组件测试指令!

Angular docs for directive testing

注:因为你把指令初始化为一个类,所以它没有任何Angular 的上下文,它只是一个类,这就是为什么inject会给你一个错误!

directive = new MyDirective(); // <- line with the problem!

Angular相关问答推荐

使用多个管道时Angel 17空数据

如何在HTML外部项目中使用Web组件(以17角创建)

具有多重签名的Angular Mocking Service

停靠的Angular 应用程序的Nginx反向代理无法加载assets资源

Toastr在独立组件上的Angular17实现

带有搜索功能的CDK-VIRTUAL-SCROLL-VIEPORT不显示该值

有Angular react 形式的输入用货币管

PrimeNg选项卡视图选项卡

Angular 懒惰地加载一个服务

当try 关闭浏览器选项卡时显示alert 时,我是否可以捕获用户是否取消警告

如何从2个api获取数据并查看Angular material 表中的数据?

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

Angular 2 中的 ChangeDetectionStrategy.OnPush 和 Observable.subscribe

如何在Angular Material2中获取活动选项卡

如何在 ngFor 循环中创建变量?

请添加@Pipe/@Directive/@Component 注解

Angular CLI 自定义 webpack 配置

如何处理Angular2中的查询参数

在angular-cli中创建模块时生成路由模块

@viewChild 不工作 - 无法读取未定义的属性 nativeElement