javascript - 如何在 Angular 6 中使用 Jasmine 将加载的数据测试为反应形式?
问题描述
我有一个 Angular 6 应用程序,它使用ngrx从商店对象将数据加载到反应式表单中。我正在尝试对此进行单元测试,但似乎无论我如何更改我的表单对象,我分配的属性总是有空白值。
这是我的代码:
HTML
<form [formGroup]="myForm" novalidate>
<input id="name" formControlName="name" />
<input id="age" formControlName="age" />
</form>
零件
export interface MyObject {
name: string;
age: string;
}
export class MyObjectComponent {
myObject: MyObject;
myForm: FormGroup;
constructor(private fb: FormBuilder, private store: Store<fromStore.State>) { }
ngOnInit() {
this.myForm = this.fb.group({
name: [null, [Validators.required]],
age: [null, [Validators.required]]
});
this.store.select(fromStore.getMyObject).subscribe(x => this.myForm.patchValue(x));
}
规格文件
describe('MyObjectComponent', () => {
let component: MyObjectComponent;
let fixture: ComponentFixture<MyObjectComponent>;
let store: Store<fromStore.State>;
let initialStateL MyObject;
let el: DebugElement;
beforeEach(async(() => {
initialState = {
name: 'My Name',
age: 55
};
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule,
HttpClientModule,
StoreModule.forRoot({}),
StoreModule.forFeature('my-object', reducer)
],
declarations: [MyObjectComponent],
providers: []
})
.compileComponents().then(() => {
fixture = TestBed.createComponent(MyObjectComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
spyOn(store, 'dispatch').and.callThrough();
fixture.detectChanges();
});
}));
it('should patch values into form', async(() => {
expect(component.myForm.controls.age.value).toBe(55);
}
}
测试总是失败,说表单中的值什么都不是。有人知道我在做什么错吗?谢谢!
解决方案
这是详细的分配:
首先为表单创建模拟值,访问您的表单并分配值,然后您需要触发组件上的更改检测,最后测试输入的值。
我还没有测试这段代码,但我认为你想要做什么真的很接近。
describe('MyObjectComponent', () => {
// Rest of code...
it('should patch values into form', async(() => {
// Mock value
const mock_age_value = 55;
fixture = TestBed.createComponent(DualityAccordionTabComponent);
const compiled = fixture.componentInstance;
// Value assignation
compiled.myForm.patchValue({
age: mock_age_value
});
// Trigger change detection
fixture.detectChanges();
expect(component.myForm.controls.age.value).toBe(55);
}
}
推荐阅读
- node.js - 我如何向网站发出请求以获取我的不和谐机器人的狗图片?
- javascript - 执行 onChange 方法后如何禁用复选框?
- c# - 继续在同一个 XML 文件上写入而不在 C# 中删除
- c# - 在此上下文中不能使用属性或索引器 - Unity v2019.3.4f1 中的错误
- python - 从给定的字母生成所有长度为 n 的字符串
- java - 安全发布和 ConcurrentHashMap
- python - 如何使用 WireShark Portable 运行 scapy?
- nginx - nginx 服务器配置错误 nginx: [emerg] /etc/nginx/nginx.conf:156 中的变量名无效
- graphql - 网络错误:响应不成功:收到状态码 400
- php - 如何主动复制其他网站的内容?