我有一个指令,在其中我通过注入关键字获取组件实例,如下所示:
export class MyDirective implements AfterViewInit {
private component: MyBaseComponent = inject(MyBaseComponent);
...
}
MyBaseComponent 是一个抽象组件,从中派生出多个其他控件(例如 MyTextComponent)。
在组件的 html 模板中使用 MyDirective 的示例:
<my-text-component my-directive>
因此“MyDirective”类中的“component”属性正在变成“my-text-component”。
问题在于单元测试是开玩笑的。
用于单元测试的空骨架代码如下所示:
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() 必须从注入上下文调用,例如构造函数、工厂函数、字段初始值设定项或与
runInInjectionContext
使用的函数。
它准确地显示了以注入()作为错误源的代码行。
PS:
在您建议将 @injectable() 装饰器添加到 MyDirective 之前,
我已经尝试过了,除了指令和组件无论如何都是默认可注入的。
您需要创建一个组件/使用现有组件来测试指令,指令无法单独初始化,这就是您收到此错误的原因,而是使用
TestBed.createComponent(MyTextComponent)
来初始化组件并通过组件测试指令!
注意:由于您将指令初始化为类,因此它没有任何角度上下文,它只是一个类,这就是注入给您错误的原因!
directive = new MyDirective(); // <- line with the problem!