speedskater / babel-plugin-rewire

A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
843 stars 90 forks source link

Rewiring doesn't work on first javascript execution pass, only later passes #171

Closed timkindberg closed 7 years ago

timkindberg commented 7 years ago

If I have the following code where I am importing something (in this case the connect function) and then using it at the top scope (not within a nested function scope):

// mycomponent.js
import { connect } from 'react-redux';

const MyComponent = () => <div>Hi</div>;

export default connect()(MyComponent);

and I try to rewire it like so:

// mycomponent.spec.js
import { MyComponent, __RewireAPI__ as TestAPI } from 'mycomponent';
import { shallow } from 'enzyme';

describe('My Component', () => {
  beforeEach(() => {
    TestAPI.__Rewire__('connect', () => (cmp) => cmp);
  });

  it('does stuff', () => {
    const wrapper = shallow(<MyComponent />);    
  });
});

In the above test case the code still throws an error talking about missing a redux store; even though I rewired the connect method to be basically a pass through that returns the component identity. All the examples on the site do not cover this sort of use case but it's very common.

Does rewire support this functionality?

speedskater commented 7 years ago

@timkindberg Thanks for opening the issue and sorry for the delay. But unfortunatly this is impossible to do. The reason is that you are rewireing the connect method after it has been used. There are two possible solutions I would propose:

Hopefully one of this solutions may help.

timkindberg commented 7 years ago

Man that is quite disappointing but I understand the technical limitation. I was hoping somehow since it was a Babel transpile time thing that we could figure this out.