I have to test this odd situation. In my html i have:
<div id="date">
<h5>
{{ showFormattedDate(myDate) }}
</h5>
</div>
The function showFormattedDate()
is defined in .ts
as follows:
showFormattedDate(dateToFormat: string): string {
return moment(dateToFormat).format('HH:mm DD/M/YYYY');
}
Now i'm trying to test this but i keep getting this error:
Expected ' Created at Invalid date ' to be '12:23 29/5/2020'.
The invalid date part is also what i see for a split of a second on the screen when the page loads but that is because the function call, i think.
I've tried testing it using these two ways:
it('should display the date correctly', async () => {
fixture.detectChanges();
// await fixture.whenStable();
// await fixture.isStable();
// await fixture.whenRenderingDone();
expect(el.query(By.css('#date')).nativeElement.textContent).toContain(
getTestData().date);
});
it('should display the date correctly (async)', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
// wait for async getQuote
fixture.detectChanges(); // update view with quote
expect(el.query(By.css('#date')).nativeElement.textContent).toContain(getTestData().date);
});
}));
But both return the aforementioned error. How could I solve this?
Calling a method within a template expression is considered bad practice in angular.So you may want to avoid that first.
Read this for more details on that.
You can make use of Angular Pipe here which will which will transform your date to your desired format and you can test the transform method of your pipe.
For more details on usage of Angular pipe click here and to know how to test your angular pipe here is a good article for the same.