Skip to content

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

@joejanuszk

Description

@joejanuszk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions