score:1

Accepted answer

i ended up solving this by creating a manual mock in the mocks folder. the key is that moment exports it's prototype with moment.fn.

import fixtures from '../__fixtures__/moment';

const moment = require.requireactual('moment');

// by default, the issame function will always return true
let issame = true;

moment.fn.issame = () => issame;
moment.fn.calendar = () => fixtures.calendar;
moment.fn.fromnow = () => fixtures.from_now;

// since format is often called with a variety of format strings, we need to
// differentiate how we are calling the function
moment.fn.format = (format) => {
    switch (format) {
    case 'mmm do yy':
        return fixtures.date;
    case 'h:mm a':
        return fixtures.time;
    case 'mmm do yy h:mm a':
        return fixtures.datetime;
    default:
        return error('unsupported format in moment mock. add case to __mocks__/moment.js');
    }
};
moment.duration.fn.humanize = () => fixtures.duration;

// this function is added to moment's prototype in order for our tests to
// change moment's issame behaviour
moment.fn.__issame = (value) => { issame = value; };

// this resets the issame behaviour back to default
moment.fn.__reset = () => {
    moment.fn.issame = () => true;
};

export default moment;

jest automatically loads this file when running the tests, and i can then test my components like:

it('renders a moment duration', () => {
    expect(wrapper.text()).toequal(fixtures.duration);
});

if i need to change the behavior of the .issame function, i can modify it with:

import moment from 'moment';

beforeall(() => {
    moment.fn.__issame(false);
});

score:0

if you are using jest to test, i can recommend you https://github.com/hustcc/jest-date-mock then you can mock current date using

advanceto(new date(2018, 5, 27, 0, 0, 0));

best practice to test is to mock fixed date and compare with result


Related Query

More Query from same tag