如何在单元测试中模拟 formControl 值 getTime()
How to mock formControl value getTime() in unit tests
我正在尝试对 formControl 的 getTime() 进行单元测试。我收到一个错误
.getTime is not a function.
组件文件的片段如下所示:
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();
...
..
.
}
您出错的原因是 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
控件。
希望对您有所帮助:)
我正在尝试对 formControl 的 getTime() 进行单元测试。我收到一个错误
.getTime is not a function.
组件文件的片段如下所示:
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();
...
..
.
}
您出错的原因是 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
控件。
希望对您有所帮助:)