Skip to content

Instantly share code, notes, and snippets.

@lalunamel
Last active February 13, 2018 15:51
Show Gist options
  • Save lalunamel/728fd45dc8f193e705daae2695f1bfb3 to your computer and use it in GitHub Desktop.
Save lalunamel/728fd45dc8f193e705daae2695f1bfb3 to your computer and use it in GitHub Desktop.
JS: Why am I able to mutate a module in a test and see my changes in my implementation file?

Why am I able to mutate a module in a test and see my changes in my implementation file?

// Test.js

import createHistory from 'history/createBrowserHistory';

describe('something', () => {
  let pushSpy;
  beforeEach(() => {
    pushSpy = jest.fn();
    createHistory = function() {
      return {
        push: pushSpy;
      }
    }
  });

  it('does something', () => {
    subject.doThing();

    // Why does this test pass if I haven't explicitly told Implementation.js
    // to use my mutated copy of createHistory?
    expect(pushSpy).toHaveBeenCalledWith("parameter")
  });
}); 

// Implementation.js

import createHistory from 'history/createBrowserHistory';

export default function doThing() {
    let history = createHistory();
    history.push("parameter")
}

Answer: When you import a module, webpack gives you a reference to the same object every time. This is because webpack caches imports. Therefore changes you make to a module imported in one file will propagate anywhere else you import that module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment