Disclaimer: I'm a beginner with Jest so please bear with me.
I'm currently working on testing a Vue2.js filter named DateFilter using Jest. This filter simply formats a date that is passed to it.
DateFilter.js
import Vue from 'vue';
import moment from 'moment';
const dateFormatter = (dateValue, dateFormat) => {
return moment(dateValue).format(dateFormat);
};
Vue.filter('date', dateFormatter);
export default dateFormatter;
So, there are three potential unit tests to be performed:
The DateFilter module should export a function
The date filter should initialize moment with the dateValue provided
The date filter should call the format method on moment using the dateFormat supplied
DateFilter.test.js
import moment from 'moment';
import DateFilter from './DateFilter';
describe('DateFilter', () => {
it('should exist', () => {
expect(DateFilter).toBeDefined();
expect(typeof DateFilter).toBe('function');
});
it('should utilize moment.format with the given dateValue and dateFormat.', () => {
// At this point, I am unsure about how to spyOn the moment function and the .format function
const mockDateFormat = `dateFormat-${Math.random()}`;
const mockDate = `mockDate-${Math.random()}`;
jest.mock('moment', () => {
return { format: jest.fn() }
});
// expect moment to have been called with mockDate
// expect moment(mockDate) to have been called with mockDateFormat
});
});