如何在单元测试中模拟formControl值getTime()

时间:2019-05-23 03:09:30

标签: angular unit-testing karma-jasmine angular-test

我正在尝试对formControl的getTime()进行单元测试。我遇到错误

  

.getTime不是函数。

该组件文件的片段如下:

import {FormControl} from @angular/forms;
@component({ 
  selector: 'lorem-ipsum',
  templateUrl: './lorem-ipsum.html'
})

export class LoremIpsumComponent implements OnInIt {
  .....
  ...
  ..
  .
  magazineSubscriptionFrom = new FormControl({value: '', disabled: true});
  magazineSubscriptionTo = new FormControl({value: '', disabled: true});

  constructor (
    ....
  ) {}

  ngOnInit() {}

  verifySubscription() {
    let test1 = this.magazineSubscriptionFrom.value.getTime();
    ...
    ..
    .
  }

1 个答案:

答案 0 :(得分:0)

发生错误的原因是,magazineSubscriptionFrom的初始值为'',因为您使用以下行在constructor中进行了设置:

magazineSubscriptionFrom = new FormControl({value: '', disabled: true});

当您尝试在其上调用getTime()时,会出现错误,因为getTime()Date的函数。因此,您在表单控件中需要一个Date值。您还需要将表单控件的字符串值转换为Date,以使getTime()正常工作

您需要更改行:

let test1 = this.magazineSubscriptionFrom.value.getTime();

let test1 = new Date(this.magazineSubscriptionFrom.value).getTime();

现在,在测试中,您需要使用setValue

设置有效日期
It is as below : It(‘should verifySubscription , () => { 
  Component.magazineSubscription.setValue(new Date()); <- set valid date here

  fixture.DetectChanges(); 

  Component.verifySubscription();
  Expect(somevalue in verifySubscription fn).toBeTruthy;
}

也可以将其更改为magazineSubscriptionTo控件。

希望它会有所帮助:)