How to write unit test for the pipe using moment.js?


#1

I am getting error TypeError: moment is not a function while I am doing a test for my pipe.

pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment-timezone';

@Pipe({ name: 'dateFormat' })
export class TimeZonePipe implements PipeTransform {
  transform(value: Date | string | number, ...args: any[]): string {
    if (!value) return '';
    return moment(value).tz(moment.tz.guess(value)).format(args[0]);
  }
}

pipe.spec.ts

import { TimeZonePipe } from './timezone.pipe';
import * as moment from 'moment-timezone';
import { inject } from '@angular/core/testing';
// import moment from 'moment';
// import 'moment-timezone';

describe('Pipe: TimeZone', () => {
  let timeZonePipe: TimeZonePipe;
  let momentT: moment;

  beforeEach(() => {
    momentT = moment;
    inject([moment], (..._) => {
      [momentT] = _;
    });
    timeZonePipe = new TimeZonePipe();

  });

  it('verify date format for MMMM Do YYYY, h:mm A z', () => {
    expect(
      timeZonePipe.transform(
        '/Date(1512383004122)/',
        'MMMM Do YYYY, h:mm A z',
      ),
    ).toBe('December 4th 2017, 4:23 AM CST');
  });

  it('verify date format for M/DD/YY hh:mm A z', () => {
    expect(timeZonePipe.transform('12/21/17', 'M/DD/YY hh:mm A z')).toBe(
      '12/21/17 12:00 AM CST',
    );
  });

  it('verify date format for M/DD/YY', () => {
    expect(timeZonePipe.transform('/Date(1576687560000)/', 'M/DD/YY')).toBe(
      '12/18/19',
    );
  });

  it('verify date format for hh:mm A', () => {
    expect(timeZonePipe.transform('/Date(1576687560000)/', 'hh:mm A')).toBe(
      '10:46 AM CST',
    );
  });

  it('verify date format for zone z', () => {
    expect(timeZonePipe.transform('/Date(1576687560000)/', 'z')).toBe('CST');
  });
});