bmt*_*heo 5 unit-testing jasmine karma-jasmine angular-ngmodel angular
我无法测试使用带有 ngModel 的自定义组件的组件
HTML 代码如下所示(在下面的 repro 中查看更多信息)
<custom-control name="formCode" [(ngModel)]="testValue"></custom-control>
Run Code Online (Sandbox Code Playgroud)
该代码在我的应用程序中运行,但在我的测试中失败并出现以下错误
Uncaught Error: Uncaught (in promise): Error: No value accessor for form control with name: 'formCode'
错误:没有名称的表单控件的值访问器:'formCode'
测试是用茉莉花运行的
我尝试了不同的导入,但似乎没有一个能解决我的问题
vhb*_*zan 14
就我而言,我使用的是未在单元测试文件中导入的自定义 Angular 组件 (SingleSelectModule)。我希望这可以帮助遇到与我相同问题的其他人:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormsModule } from '@angular/forms';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CaselistComponent } from './caselist.component';
import { SingleSelectModule } from '@uimf/uitk/components/single-select';
describe('Component: CaselistComponent', () => {
let component: CaselistComponent;
let fixture: ComponentFixture<CaselistComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
...
],
imports: [
FormsModule,
SingleSelectModule,
RouterTestingModule,
HttpClientTestingModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
});
});
Run Code Online (Sandbox Code Playgroud)
小智 8
这是因为您在测试中模拟了 CustomControlComponent。在 package.json 中安装 @angular/material 及其依赖项,并使用下面的规范文件。测试将通过。
https://stackblitz.com/edit/angular-test-ng-model-vsk5re
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule, NG_VALUE_ACCESSOR, DefaultValueAccessor, ControlValueAccessor } from '@angular/forms';
// import { MockComponent } from 'ng2-mock-component';
import{MatFormFieldModule, MatInputModule} from '@angular/material';
import { ParentControlComponent } from './parent-control';
import {CustomControlComponent} from '../custom-control/custom-control';
describe('ParentControlComponent', () => {
let component: ParentControlComponent;
let fixture: ComponentFixture<ParentControlComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
CustomControlComponent,
ParentControlComponent,
// MockComponent({ selector: 'custom-control' }),
],
imports: [
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule
],
providers: [
]
})
.compileComponents();
fixture = TestBed.createComponent(ParentControlComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18281 次 |
| 最近记录: |