一个最小的工作示例,在一个新的 Angular 15 CLI 应用程序中:
HelperService
DemoPipe
调用注入 inject()
:export class DemoPipe implements PipeTransform {
private readonly helper = inject(HelperService);
...
}
NG-cli 创建的默认管道测试将失败,因为构造函数调用发生在 DI 上下文之外:
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 })
我可以在 Karma 中使用任何包装器来提供缺少的环境吗?
您可以尝试以下方法:
describe('DemoPipe', () => {
let pipe:DemoPipe;
beforeEach(async () => {
TestBed.configureTestingModule({ providers: [DemoPipe,HelperService] });
});
it('create an instance', () => {
pipe = TestBed.inject(DemoPipe);
expect(pipe).toBeTruthy();
});
我试过了,它有效