单元测试FormGroup / FormArray

时间:2018-12-19 14:15:02

标签: angular forms unit-testing form-control

我有一个接受AbstractControl变量并执行以下操作的函数:

new(item: AbstractControl) {
  item['controls'].myArray.push(
    this.formBuilder.group({
      // my attributes here
    )}
  )
}

执行console.log(item)时的对象结构如下(我只显示了重要信息):

FormGroup {
  controls: {
    …,
    items: FormArray { 
      …,
      controls: Array(5) [FormGroup, FormGroup, …] 
  }
}

但是我似乎无法对其进行正确的测试...

it('Should add', () => {
    const fb = new FormBuilder();
    const myObject = fb.group([example]);

    component.new(myObject);

    const packagesLength = component.myFormGroup.get('data')['controls'][0]['controls']['items']['controls'].length;

    expect(packagesLength).toEqual(2);
  });

我从控制台得到的就是

  

无法读取未定义的属性“ push”

如果我从FormBuilder.group中删除数组括号(即fb.group(example);,则会收到消息:

  

customer.controls.packages.push不是函数

1 个答案:

答案 0 :(得分:0)

您是否不需要在测试中添加名称为“ myArray”的formArray而不是formGroup中没有控件名称的数组?像这样:

-- Table structure for table `matakuliah`

CREATE TABLE `matakuliah` (
  `prodi` varchar(5) DEFAULT NULL,
  `kodemk` varchar(10) DEFAULT NULL,
  `namamk` varchar(128) DEFAULT NULL,
  `sks` tinyint(4) DEFAULT NULL,
  `skst` tinyint(4) DEFAULT NULL,
  `sksp` tinyint(4) DEFAULT NULL,
  `sksl` tinyint(4) DEFAULT NULL,
  `smt` tinyint(4) DEFAULT NULL,
  `kelompok` varchar(5) DEFAULT NULL,
  `kompetensi` char(3) DEFAULT NULL,
  `tahunkur` varchar(4) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- Sample data for table `siska_matakuliah`
--

INSERT INTO `matakuliah` (`prodi`, `kodemk`, `namamk`, `sks`, `skst`, `sksp`, `sksl`, `smt`, `kelompok`, `kompetensi`, `tahunkur`) VALUES
('57601', '112001', 'PRAKTEK KERJA & LAPORAN', 2, 0, 0, 2, 2, '', '111', '2003'),
('57601', '112102', 'TUGAS AKHIR (APLIKASI)', 2, 0, 0, 2, 2, '', '111', '2003'),
('57601', '111001', 'SISTEM OPERASI', 2, 1, 1, 0, 1, '', '111', '2003'),
('57601', '111101', 'INTRANET & INTERNET', 2, 1, 1, 0, 1, '', '111', '2003'),
('57601', '111401', 'PENGELOLAAN INSTALASI KOMPUTER', 2, 1, 1, 0, 1, '', '111', '2003'),
('57601', '110001', 'PENDIDIKAN AGAMA ISLAM', 2, 2, 0, 0, 1, '', '111', '2003'),
('57601', '110002', 'PENDIDIKAN AGAMA KRISTEN PROTESTAN', 2, 2, 0, 0, 1, '', '111', '2003'),
('57601', '110003', 'PENDIDIKAN AGAMA KRISTEN KATOLIK', 2, 2, 0, 0, 1, '', '111', '2003'),
('57601', '110004', 'PENDIDIKAN AGAMA HINDU', 2, 2, 0, 0, 1, '', '111', '2003'),
('57601', '110005', 'PENDIDIKAN AGAMA BUDDHA', 2, 2, 0, 0, 1, '', '111', '2003');


-- Table structure for table `kuliah`

CREATE TABLE `kuliah` (
  `kodesmt` varchar(5) DEFAULT NULL,
  `prodi` varchar(5) DEFAULT NULL,
  `nimhs` varchar(8) DEFAULT NULL,
  `kodemk` varchar(10) DEFAULT NULL,
  `nilai` char(1) DEFAULT NULL,
  `presensi` varchar(35) NOT NULL,
  `paralel` char(2) DEFAULT NULL,
  `kodekelas` varchar(9) DEFAULT NULL,
  `status` char(1) NOT NULL,
  `id_krs` char(32) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;