How can I check element rendering using date protocol in Angular 2?

I cannot verify the component that uses the Date pipe in Angular 2 (using Karma via PhantomJS). When I try, I get the ORIGINAL EXCLUSION: ReferenceError: Can't find the variable: Intl

Here is my entire specification file:

import { provide, PLATFORM_PIPES } from '@angular/core'; import { DatePipe } from '@angular/common'; import { addProviders, async, inject } from '@angular/core/testing'; import { Post, PostComponent, PostHtmlComponent } from './'; import { usingComponentFixture } from '../../test-helpers'; describe('Component: Post', () => { beforeEach(() => { provide(PLATFORM_PIPES, {useValue: DatePipe, multi: true }); addProviders([PostComponent, PostHtmlComponent, ]); }); it('should render an h1 tag with text matching the post title', usingComponentFixture(PostComponent, fixture => { let component = <PostComponent>fixture.componentInstance; let element = fixture.nativeElement; component.post = <Post>{ title: 'Hello', publishedOn: new Date('8/5/2016') }; fixture.detectChanges(); expect(element.querySelector('.blog-post-header h1').innerText).toBe('Hello'); }) ); }); 

And this is the component template:

  <div class="col-lg-8 col-md-7 col-sm-6"> <h1>{{post.title}}</h1> <p class="lead">{{post.publishedOn | date:'fullDate'}}</p> </div> 
+7
source share
3 answers

I was able to solve this problem. Here is what I had to do:

  • npm install karma-intl-shim --save-dev
  • Add 'intl-shim' to the framework collection in karma.conf.js file
  • Add the following to karma-test-shim.js (this is specified in the karma.conf.js file collection)

     require('karma-intl-shim'); require('./en-us.js'); // copied from https://github.com/andyearnshaw/Intl.js/blob/master/locale-data/json/en-US.json Intl.__addLocaleData(enUsLocaleData); 
+6
source

For tests, I mock the date of the pipe:

 @Pipe({ name: 'date', pure: false // required to update the value when the promise is resolved }) export class MockedDatePipe implements PipeTransform { name: string = 'date'; transform(query: string, ...args: any[]): any { return query; } } 

Then, when I configure the testing module, I insert it into the declaration:

 TestBed.configureTestingModule( { providers: [ SelectionDispatcher, { provide: MyService, useClass: MockedMyServiceService } ], declarations: [ MyComponent, MockedTranslatePipe, MockedDatePipe ] }); 
+4
source

let pipe = new DatePipe ('en');

expect (page.myDate.nativeElement.innerHTML) .toBe (pipe.transform (model.date, 'dd / MM / yyyy);

0
source

All Articles