ReactLibraries / storybook-addon-module-mock

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

Prevent real module from getting executed on the browser #19

Closed musjj closed 1 month ago

musjj commented 1 month ago

I'm trying to make a story for a component that imports a server-only function, like this:

import * as dataGetters from "./get-data.ts";

export const Default: Story = {
  parameters: {
    moduleMock: {
      mock: () => {
        const getUser = createMock(dataGetters, "getUser");
        getUser.mockImplementation(() => Promise.resolve(undefined));

        return [db];
      },
    },
  }
}

But the module I'm trying to mock has side effects:

get-data.ts

import { dbClient } from "my-orm";

const db = dbClient.connect(); // Connect to the database

export function getUser() {
  return db.user.findAll();
};

(this is a huge simplification)

But the story fails to build because the database client (obviously) doesn't work in the browser.

It looks like that the module was imported (causing the db client to be executed), before it could be mocked. Is there a way to make sure that the module never gets executed?