dimanche 21 octobre 2018

Jest mock value per test

I want to test if a library function is not called when token value is null. To do this I must change mock value of GOOGLE_ANALYTICS_TRACKING_ID between unit tests. It is stored in 'config.js' which looks like that:

module.exports = {
  GOOGLE_ANALYTICS_TRACKING_ID: process.env.GOOGLE_ANALYTICS_TRACKING_ID
};

Also it is used by withGoogleAnalytics which is a HOC. Inside it I'm importing config this way:

import { GOOGLE_ANALYTICS_TRACKING_ID } from 'config';

My test looks like that:

import React from 'react';
import { shallow } from 'enzyme';
import ReactGA from 'react-ga';

import withGoogleAnalytics from '../withGoogleAnalytics';

jest.mock('react-ga', () => ({
  pageview: jest.fn(),
  initialize: jest.fn()
}));

jest.mock('config', () => ({ GOOGLE_ANALYTICS_TRACKING_ID: '123' }));

const Component = withGoogleAnalytics(() => <div />);

describe('HOC withGoogleAnalytics', () => {
  describe('render', () => {
    const shallowWrapper = shallow(<Component />);

    it('should fire initialize action', () => {
      expect(ReactGA.initialize).toHaveBeenCalledWith('123');
    });

    it('should have pageview prop set', () => {
      expect(shallowWrapper.prop('pageview')).toBe(ReactGA.pageview);
    });

    it('should not fire initialize action', () => {
      expect(ReactGA.initialize).not.toHaveBeenCalled();
    });
  });
});

From what I read on StackOverflow and GitHub I should be able to do it using jest.resetModules() and jest.mockImplementation() but all the examples were mocking functions. Here I need to change string value between tests. How can I do it?

Aucun commentaire:

Enregistrer un commentaire