ReactLibraries / storybook-addon-module-mock

Provides module mocking functionality like jest.mock on Storybook.
MIT License
42 stars 5 forks source link

Issue setting up Chromatic with mock in project - 'Failed to write mock' error #7

Closed harry-wang-faire closed 1 year ago

harry-wang-faire commented 1 year ago

Description: I am attempting to set up Chromatic in my project, along with a mock, which requires me to build it first. However, I am encountering an error: 'Failed to write mock.' My app setup follows the same configuration as sample 2 in the readme.

After conducting some investigation, I discovered that the moduleId const moduleName = module.constructor.prototype.__moduleId__; is defined when I run storybook dev -p 6006. However, it is stripped out after running storybook build and npx http-server storybook-static. I also attempted to manually trigger this piece of code:

if (descriptor === null || descriptor === void 0 ? void 0 : true) {
    const f = module[name];
    module[name] = fn;
    fn.mockRestore = () => {
        module[name] = f;
    };
}

However, I encountered the error: Cannot set property {mockComponent} of #<Object> which has only a getter. Interestingly, when I attempted to mock with a React component, I didn't experience this issue. I have a feeling that it might be related to Webpack, but I'm currently unable to find a solution that works.

Additional information:

Storybook version: 7 Framework: @storybook/react-webpack5

harry-wang-faire commented 1 year ago

I ended up finding that turn off the strict mode in the babel plugin will resolve the issue.


          '@babel/plugin-transform-modules-commonjs',
          {
            loose: true,
            strictMode: false,
          },
        ]```