linearlabs-workspace / storybook-addon-mock

This addon allows you to mock fetch or XMLHttpRequest in the storybook.
https://storybook-addon-mock.netlify.app
MIT License
112 stars 43 forks source link

Mocked fetch does not work if fetch resource is not a URL string #140

Open joejanuszk opened 1 year ago

joejanuszk commented 1 year ago

The fetch API supports not only strings that represent URLs, but also objects with a stringifier that provides a URL. An instance of a URL object is an example of such an object.

Source: https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters

However, I found that mocked requests do not work if the resource supplied to fetch is an instance of a URL object. For instance:

const someFakeUrl = `${window.location.origin}/foo/bar`;
const someFakeUrlObj = new URL(someFakeUrl);

SomeStory.parameters = {
  mockData: [
    {
      url: someFakeUrl,
      method: 'GET',
      status: 200,
      response: {
        data: 'hello world',
      },
    },
  ],
};

// works
fetch(someFakeUrl).then((res) => {
  // do something
});

// does not work
fetch(someFakeUrlObj).then((res) => {
  // do something
});

In the case where the argument to fetch is someFakeUrl (a string), storybook-addon-mock will exhibit the expected behavior, i.e. the network request will be intercepted and the response will contain the mocked data.

In the case where the argument to fetch is someFakeUrlObj (an instance of URL), storybook-addon-mock will not attempt to intercept the request.

Please note that I observed this issue in an environment with a "real" domain, i.e. not localhost. It seemed like internally, storybook-addon-mock may be normalizing the URL provided to fetch to a localhost value, which is not correct behavior based on the construction described above using window.location.origin in a non-localhost environment.

nutboltu commented 1 year ago

@joejanuszk In the current version of this addon, it only supports string as an URL. We can take both string and URL objects as a parameter. I am considering this as a feature request.

Any PR is welcome :)