我有一个 Angular 16 组件,它通过它所在的表单,并且允许viewProviders
它工作,这是我收到的另一个问题的答案
@Component({
selector: 'app-question-form-editor',
standalone: true,
imports: [ CommonModule, FormsModule ],
templateUrl: './question-form-editor.component.html',
viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
})
export class QuestionFormEditorComponent implements OnInit {
@Input() form!: NgForm;
//Logic goes here...
}
现在这可以按预期工作,但是现在我的单元测试中断了,因为他们需要这个提供程序,并且我不确定我需要提供什么值。
const mockQuestionForm = new NgForm([], []);
mockQuestionForm.form.addControl('example', new FormControl('', Validators.required));
describe('QuestionFormEditorComponent', () => {
let component: QuestionFormEditorComponent;
let fixture: ComponentFixture<QuestionFormEditorComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [QuestionFormEditorComponent],
providers: [{ provide: ControlContainer, useValue: mockQuestionForm }],
});
fixture = TestBed.createComponent(QuestionFormEditorComponent);
component = fixture.componentInstance;
component.form = mockQuestionForm;
});
it('should create', () => {
fixture.detectChanges(); //triggers ngOnInit()
expect(component).toBeTruthy();
});
});
我也尝试过useExisting
,并且useValue
尝试过,NgForm
而不是我的mockQuestionForm
- 都有相同的结果
这是 Jasmine 失败的错误消息
NullInjectorError: R3InjectorError(Standalone[QuestionFormEditorComponent])[NgForm -> NgForm -> NgForm]:
NullInjectorError: No provider for NgForm!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'NgForm', 'NgForm', 'NgForm' ] })
at NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:8890:27)
at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9334:33)
at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9334:33)
at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9334:33)
at ChainedInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:14018:36)
at lookupTokenUsingModuleInjector (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:4608:39)
at getOrCreateInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:4656:12)
at ɵɵdirectiveInject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:11801:19)
at ɵɵinject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:848:60)
at NodeInjectorFactory.factory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9556:29)
您应该能够覆盖组件注释设置,如下所示:
(代码示例来自这里)
就您而言,我认为您缺少 FormsModule 和/或 ReactiveFormsModule ...我建议尝试将它们导入到您的测试模块中,并在执行此自定义步骤之前查看是否可以解决您的问题。