Thursday, 26 July 2018

Mocking es6 module returning factory function (moment.js)

Caveat: I'm new to Jest so bear.

I am attempting to test a Vue2.js filter using Jest called DateFilter. This filter simply applies a date format to a date 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, I see three valid unit tests here

  1. The DateFilter module should export a function

  2. The date filter should initialize moment with the dateValue passed

  3. The date filter should call the format method on moment with the dateFormat passed

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 moment.format with the dateValue and dateFormat passed.', () => {
        // Here I get lost in how to spyOn 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
    });
});



from Mocking es6 module returning factory function (moment.js)

No comments:

Post a Comment