英文:
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('create an instance', () => {
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('DemoPipe', () => {
let pipe:DemoPipe;
beforeEach(async () => {
TestBed.configureTestingModule({ providers: [DemoPipe,HelperService] });
});
it('create an instance', () => {
pipe = TestBed.inject(DemoPipe);
expect(pipe).toBeTruthy();
});
I tried and it works
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论