In order to verify if a function called haveBeenCalledWith()
includes the necessary parameters, I am seeking to validate the correctness of my call without actually executing the real methods.
I have experimented with multiple solutions sourced from various places such as this post on Stack Overflow and another one found on Jasmine JS group discussion.
You can find my attempts documented in a Plunker that might offer some insights here
Currently, I am utilizing an external library called date-fns.
The Angular 4 Pipe I created looks like this:
import { Pipe, PipeTransform } from '@angular/core';
// Importing all 'date-fns' works but causes issues with tree shaking, so it's not ideal
import * as format from 'date-fns/format';
@Pipe({
name: 'dateFnsFormat'
})
export class DateFnsFormatPipe implements PipeTransform {
transform(value: any, args?: any): any {
return format(value, args);
}
}
My objective is to test the invocation of the format
function.
Below are my testing scenarios without mock implementations:
import * as format from 'date-fns/format';
const xmasDay = '2017-12-25 12:30:00';
// Succeeds with actual function
it('should transform the date from Y-m-d H:m:s to d/m/Y', () => {
const dateFnsFormatPipe = new DateFnsFormatPipe();
expect(dateFnsFormatPipe.transform(xmasDay, 'DD/MM/YYYY')).toBe('25/12/2017');
});
// Succeeds with actual function
it('should transform the date from Y-m-d H:m:s to d/m/Y H:m:s', () => {
const dateFnsFormatPipe = new DateFnsFormatPipe();
expect(dateFnsFormatPipe.transform(xmasDay, 'DD/MM/YYYY HH:mm:ss')).toBe('25/12/2017 12:30:00');
});
Here, I describe my various attempts along with the encountered errors:
// #1 Attempt using spyOn(window, 'function');
// Error: Error: format() method does not exist
it('#1 should transform the date from Y-m-d H:m:s to d/m/Y H:m:s', () => {
spyOn(window, 'format');
const dateFnsFormatPipe = new DateFnsFormatPipe();
dateFnsFormatPipe.transform(xmasDay, 'DD/MM/YYYY HH:mm:ss');
expect(window.format).toHaveBeenCalled();
});
// #1b Attempt using spyOn(global, 'function');
// Error: Error: format() method does not exist
it('#1b should transform the date from Y-m-d H:m:s to d/m/Y H:m:s', () => {
spyOn(global, 'format');
const dateFnsFormatPipe = new DateFnsFormatPipe();
dateFnsFormatPipe.transform(xmasDay, 'DD/MM/YYYY HH:mm:ss');
expect(global.format).toHaveBeenCalled();
});
...
... (More attempts included)
...
Note: Although I am demonstrating examples within the date-fns
library, my intention is to implement the same concept with diverse libraries. Additionally, I aim to avoid importing the main file due to concerns regarding tree shaking when leveraging webpack.