theKashey / rewiremock

The right way to mock dependencies in Node.js or webpack environment.
MIT License
491 stars 31 forks source link

Storybook rewire __mocks__ #105

Closed Meemaw closed 4 years ago

Meemaw commented 4 years ago

Hi!

I'm trying to use rewiremock to mock our dependencies in Storybooks. We already have __mocks__ folder which are used in our tests and we would like to re-use those for our storybooks. Based on the https://github.com/theKashey/rewiremock#automocking those should be mocked automatically.

I don't see that happening.

We are using:

.babelrc

{
  "presets": ["react-app"],
  "plugins": ["rewiremock/babel"]
}

.webpack.config.js

module.exports = ({ config }) => {
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve('babel-loader'),
        options: {
          presets: [
            [
              'react-app',
              {
                flow: false,
                typescript: true,
              },
            ],
          ],
        },
      },
    ],
  });
  config.resolve.extensions.push('.ts', '.tsx');

  config.plugins.push(...[new (require('rewiremock/webpack/plugin'))()]);

  return config;
};

There must be something obvious that I am missing. Any idea?

theKashey commented 4 years ago

You have to include rewiremock to every story you want to have mocks enabled, imported before any dependencies you want to mock (if you are using babel plugin)

Meemaw commented 4 years ago

It is possible to get that working without having to do that in every story? (Using CRA v3.2)

theKashey commented 4 years ago

Probably. Let me first ask you what you are going to mock, and why. Keep in mind - you might change your code behaviour using environment variables as well as mock files using webpack aliases.

Meemaw commented 4 years ago

I would like to mock some of the SDKs that we use in application that do API calls by default. We already mock them in tests via Jest and __mocks__ folder.

In our application we use absolute imports, e.g:

import X from "@scope/sdk"

We then have a @scope directory inside __mocks__ directory with a sdk.ts file that we want to use instead of the actual dependency. In jest this file gets automatically resolved/mocked and I would like the same for storybooks.

theKashey commented 4 years ago

In this case webpack aliases, configurable via storybook's webpack.conf would be the best way.

{
resolve: {
  alias: {  
    "@scope/sdk": "path to a __mocks__",
  }
}
Meemaw commented 4 years ago

This worked -- thanks.