如何测试具有自定义依赖项的 Angular 管道(使用 NG 15 inject() 进行注入)?

huangapple go评论64阅读模式
英文:

How to test a Angular pipe with own dependencies (injected with NG 15 inject())?

问题

Here is the translated content you requested:

在一个新的Angular 15 CLI应用中的最小工作示例:

* 一个(空白)服务 `HelperService`
* 这个服务通过新的 `inject()` 调用注入到 `DemoPipe` 中:
```typescript
export class DemoPipe implements PipeTransform {
  private readonly helper = inject(HelperService);
  ...
}

由NG-cli创建的默认管道测试将失败,因为构造函数调用发生在DI上下文之外:

it('创建一个实例', () => {
  const pipe = new DemoPipe();
  expect(pipe).toBeTruthy();
});
错误:NG0203:inject() 必须从注入上下文中调用,如构造函数、工厂函数、字段初始化程序或与 `EnvironmentInjector#runInContext` 一起使用的函数。详细信息请参阅 https://angular.io/errors/NG0203
        错误属性:Object({ code: -203 })

是否有任何Karma包装器可以提供缺失的环境?


<details>
<summary>英文:</summary>

A minimum working example, in a fresh Angular 15 CLI app:

* A (blank) service `HelperService`
* This service gets injected into `DemoPipe` with the new `inject()` call:
```typescript
export class DemoPipe implements PipeTransform {
  private readonly helper = inject(HelperService);
  ...
}

The default pipe test created by NG-cli will fail, as the constructor call happens outside the DI context:

it(&#39;create an instance&#39;, () =&gt; {
  const pipe = new DemoPipe();
  expect(pipe).toBeTruthy();
});
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203
        error properties: Object({ code: -203 })

Is there any wrapper I could use in Karma to provide the missing environment?

答案1

得分: 3

你可以尝试以下代码:

describe('DemoPipe', () => {
 let pipe: DemoPipe;

  beforeEach(async () => {
    TestBed.configureTestingModule({ providers: [DemoPipe, HelperService] });
  });

  it('create an instance', () => {
    pipe = TestBed.inject(DemoPipe);
    expect(pipe).toBeTruthy();
  });
}

我尝试过,它可以正常工作。

英文:

You can try the following:

describe(&#39;DemoPipe&#39;, () =&gt; {
 let pipe:DemoPipe;

  beforeEach(async () =&gt; {
    TestBed.configureTestingModule({ providers: [DemoPipe,HelperService] });
  });

it(&#39;create an instance&#39;, () =&gt; {
  pipe = TestBed.inject(DemoPipe);
  expect(pipe).toBeTruthy();
});

I tried and it works

huangapple
  • 本文由 发表于 2023年4月17日 19:20:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定