Skip to content

Instantly share code, notes, and snippets.

@danyg
Last active August 8, 2019 08:05
Show Gist options
  • Save danyg/1dc566bd255f6f0fb5e056da5e1e7cc9 to your computer and use it in GitHub Desktop.
Save danyg/1dc566bd255f6f0fb5e056da5e1e7cc9 to your computer and use it in GitHub Desktop.
How to use Wrappers in Tests

So in order to avoid this, we use wrappers which are easier to mock:

const defineGlobalWindow = (locationValue?: string) => {
  global.window = Object.create(window);
  const url = locationValue || "spTestHost";
  Object.defineProperty(window, "location", {
    value: { hostname: url },
    writable: true
  });
};

Code to be tested

import wrappers from 'utils/wrappers';

export default const getConfig = () => {
  if(wrappers.getLocation() === LOCALHOST) {
    // do something in localhost
  }
...
}

utils/wrappers

const getLocation = () => window.location;

export default {
  getLocation
};

utils/wrappers-mock

import wrappers from './wrappers';

const defaultWrappers = {
  ...wrappers
};


export default {
  wrappers,

  mock(key, mock) {
      wrappers[key] = mock
  },

  restore(key) {
    wrappers[key] = defaultWrappers[key];
  }
};

Test

import wrappersMock from 'utils/wrappers-mock';

afterEach(() => wrappersMock.restore('getLocation'));

it('config do something when in localhost', () => {
  wrappersMock.mock('getLocation', () => 'http://localhost');

  const result = getConfig();

  expect(result).toBe(something);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment