0

I am trying to unit test a formControl's getTime(). I am getting an error

.getTime is not a function.

A snippet of the component file looks like:

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();
    ...
    ..
    .
  }
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • Can you also post your test code – asimhashmi May 23 '19 at 03:31
  • @HDJEMAI ... tq for formatting.... I will do a better job next time – Ineedsunnydays May 23 '19 at 03:32
  • May be you can try to use [spyOnProperty](https://stackoverflow.com/questions/43928209/how-to-get-jasmines-spyonproperty-to-work) – HDJEMAI May 23 '19 at 03:33
  • ``spyOnProperty(component.magazineSubscriptionFrom, 'value', 'get').and.returnValue(your date value here)`` ? – HDJEMAI May 23 '19 at 03:36
  • take a look here, it may help as well: [How to unit test a FormControl in Angular2](https://stackoverflow.com/questions/39481324/how-to-unit-test-a-formcontrol-in-angular2) – HDJEMAI May 23 '19 at 03:52
  • 1
    It is as below : It(‘should verifySubscription , () => { Component.magazineSubscription.setValue(‘’); fixture.DetectChanges(); Component.verifySubscription(); Expect(somevalue in verifySubscription fn).toBeTruthy; } – Ineedsunnydays May 23 '19 at 03:54

1 Answers1

0

The reason for your error is that the initial value of magazineSubscriptionFrom is '' since your are setting it in your constructor using line:

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

When you try to call getTime() on it, it will give you the error because getTime() is a function for Date. So you need a Date value in in your form control. You also need to convert the string value of your form control to Date in order for getTime() to work

You need to change line:

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

to

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

Now in your test you need to set the valid date using 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;
}

Also change it for magazineSubscriptionTo control.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
asimhashmi
  • 4,258
  • 1
  • 14
  • 34