Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
ninigi Avatar asked Dec 31 '25 22:12

ninigi


1 Answers

A module that relies on mocked module should be imported after jest.mock. This won't happen if import is located in module scope and jest.mock is done per test.

Assigning shallowWrapper once for entire suit is bad and results in test cross-contamination.

It should be:

let shallowWrapper;
let withGoogleAnalytics;

beforeEach(async () => {
  shallowWrapper = shallow(<Component />)
  jest.mock('config', () => ({ GOOGLE_ANALYTICS_TRACKING_ID: '123' }));
  withGoogleAnalytics = (await import('../withGoogleAnalytics')).default;
});

If there's a need to test with another GOOGLE_ANALYTICS_TRACKING_ID value, another describe with block with different beforeEach can be created.

like image 164
Estus Flask Avatar answered Jan 03 '26 10:01

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!