Angular单元测试以@Input形式传递FormGroup
创始人
2024-10-23 22:30:12
0

在Angular中,可以使用@Input()装饰器将FormGroup传递给组件。以下是一个示例解决方案:

在父组件中,定义一个FormGroup并将其传递给子组件:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-parent',
  template: `
    
  `
})
export class ParentComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
    });
  }
}

在子组件中,使用@Input()装饰器接收FormGroup

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-child',
  template: `
    
` }) export class ChildComponent { @Input() formGroup: FormGroup; }

现在,我们可以在单元测试中使用TestBed来测试子组件接收到的FormGroup是否正确。以下是一个测试示例:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ChildComponent } from './child.component';
import { FormGroup, FormControl, Validators } from '@angular/forms';

describe('ChildComponent', () => {
  let component: ChildComponent;
  let fixture: ComponentFixture;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ ChildComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should receive and display formGroup', () => {
    const formGroup = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
    });

    component.formGroup = formGroup;
    fixture.detectChanges();

    const inputElements = fixture.nativeElement.querySelectorAll('input');
    expect(inputElements.length).toBe(2);
    expect(inputElements[0].value).toBe('');
    expect(inputElements[1].value).toBe('');
  });
});

在这个测试中,我们首先创建了一个FormGroup并将其赋值给子组件的formGroup属性。然后,我们使用fixture.nativeElement.querySelectorAll('input')来获取子组件中的所有输入元素,并断言它们的数量及初始值是否正确。

通过这种方式,我们可以确保子组件成功接收到了父组件中传递的FormGroup

相关内容

热门资讯

黑科技存在(微扑克软件)wpk... 黑科技存在(微扑克软件)wpk线上德州俱乐部原先真的有挂!太嚣张了原生存在有挂(2022已更新)(哔...
黑科技玄学(we-poke)德... 黑科技玄学(we-poke)德州wepower一直是真的有挂!太嚣张了都是真的是有挂(2022已更新...
黑科技线上(wpk稳赢)gg扑... 黑科技线上(wpk稳赢)gg扑克确实有挂!太夸张了原先存在有挂(2022已更新)(哔哩哔哩)是一款可...
黑科技能赢(约局吧发牌逻辑)W... 黑科技能赢(约局吧发牌逻辑)WPK好像存在有挂!太坑了一贯有挂(2024已更新)(哔哩哔哩);超受欢...
黑科技好牌(微扑克游戏)扑克世... 这是一款非常优秀的微扑克游戏 ia辅助检测软件,能够让你了解到微扑克游戏中牌率当中全部隐藏参数,与同...
黑科技辅助(微扑克模拟器)We... 相信很多朋友都在电脑上玩过微扑克模拟器吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编给大家带来...
黑科技辅助挂(微扑克发牌)德州... 1、黑科技辅助挂(微扑克发牌)德州nzt真是是真的有挂!太夸张了原本真的是有挂(2023已更新)(哔...
黑科技ai(Wepoke插件)... 黑科技ai(Wepoke插件)AAPOKer原生存在有挂!太无语了从来有挂(2020已更新)(哔哩哔...
黑科技软件(Wepoke代码)... 黑科技软件(Wepoke代码)德州wpk一贯有挂!太无语了素来是有挂(2024已更新)(哔哩哔哩);...
黑科技真的(Wepoke开挂)... 黑科技真的(Wepoke开挂)wpk德州一向真的有挂!太嚣张了真是有挂(2022已更新)(哔哩哔哩)...