Monday, 1 July 2019

Require from the actual file using NormalModuleReplacementPlugin

I have a Storybook setup for which I need for my React component's children components to stop doing API calls. The setup is quite complex, and it is also irrelevant to the question, so I'll just say that I need the components to stop doing API calls.

My ultimate goal is to have the children component stay in a "loading state" forever, so mocking the server response not a solution here.

The approach that I came up with was to replace my Thunk action creators with a stubbed one. Similar to what we do on Jest unit tests

// note that I'm using redux ducks: https://github.com/erikras/ducks-modular-redux

jest.mock('./ducks/students');

Of course the above doesn't work since Storybook doesn't run on Jest. So my current approach is to use the NormalModuleReplacementPlugin to replace the real module ducks/students.js with a stubbed one ducks/stubs/students.js which contains the functions, but with an empty body:

// ./ducks/students.js
export const loadResources() = fetch('/resources');

export default (state, actions => {
  // reducer's body
}


// ./ducks/stubs/students.js
export const loadResources() = Promise.resolve();  // STUBBED

export default (state, actions => {
  // reducer's body
}

The problem is that I need only the thunk action creators to be stubbed, everything else in the file (other actions, and reducer) needs to be the same.

This are the approaches I have considered so far to fix this:

  • Copy/paste the rest of the actual file into the stubbed one. This wouldn't scale.
  • Attempting to use require.requireActual(). It turns out this is a Jest custom function so I can't use it on Storybook.

Ideally I could find a way to import everything from the actual module into the stubbed one, and export the stubbed functions and the rest of the real functions that I need.

Any ideas how can I access the actual module from the stubbed one when I'm using NormalModuleReplacementPlugin?



from Require from the actual file using NormalModuleReplacementPlugin

No comments:

Post a Comment