Giter Club home page Giter Club logo

storybook-addon-mock's Introduction

Storybook addon mock

Storybook Addon Mock

Actions Status Npm download npm version License

NPM

This addon allows you to mock fetch or XMLHttprequest requests in storybook. If your component depends on backend requests, and your backend requests are not ready yet to feed your component, this addon provides mock response to build your component.

Purpose

There are few packages those help the developers to mock the backend requests while building components. But those packages aren't integrated properly in storybook and also there's no scope to play with those requests in the storybook. Mostly, there's no playground to modify the response and see the changes in the storybook.

Highlights

storybook-addon-mock provides the following features.

  • You can mock fetch or XMLHttpRequest.
  • A dedicated panel where you can see the list of mock requests.
  • An on/off button for each request which can turn off the mock and try the real request.
  • A dropdown list of status code where you can change the status and experience the difference.
  • A response JSON object which can be modified in the panel. You can see the changes straight away in the story.
  • A delay option which helps you delaying the response so that you can test any kind of loading behaviour.

Documentation

See the documentation

Older(2.*) version documentation

License

This project is licensed under the MIT License - see the LICENSE file in the source code for details.

storybook-addon-mock's People

Contributors

a-ursino avatar angelod1as avatar berniegp avatar carloschneider avatar coderkevin avatar dependabot[bot] avatar extempl avatar fooloomanzoo avatar itamargronich avatar joaobrlt avatar jontii avatar katarzynab99 avatar mchill avatar moroine avatar mribichich avatar nicolasbonduel avatar nring avatar nutboltu avatar reddy-hari avatar schonert avatar stof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

storybook-addon-mock's Issues

Problem with multiple mocks in the same story.

I am trying to mock multiple requests for the same component, such as:

Appointment.parameters = {
  mockData: [
    {
        url: `${process.env.ENDPOINT}/appointments/CURRENT`,
        response: responses.CURRENT,
    },
    {
        url: `${process.env.ENDPOINT}/appointments/EARLY`,
        response: responses.EARLY,
    },
    {
        url: `${process.env.ENDPOINT}/appointments/LATE`,
        response: responses.LATE,
    },
    {
        url: `${process.env.ENDPOINT}/appointments/CANCELLED`,
        response: responses.CANCELLED,
    },
  ],
};

It seems that only the latest mockData of the array is used, and the other ones are ignored. Am I doing something wrong?

V3: Create a monorepo and spearate the docs and the addon into different packages

This is a large feature. This issue is aimed at completing the following tasks

  • create a monorepo with yarn workspaces
  • move the addon and the docs into separate packages
  • Move the readme into docs using storybook docs addon.
  • Improve the docs
    • Introduction, Installation, and User guide
    • Examples should be split into different packages e.g fetch, Axios, superagent, SWR
    • How to contribute
  • More tests
  • Use the Storybook addon kit tool
  • Supports parameters for each story. Currently, it only supports parameter per component.

Duplicate Data in response

Hey,
Thanks for your plugin, In last version 3.0.0, the data attribute appear twice in the response when using it with axios.

image

parameters: {
    mockData: [
      {
        url: 'https://XXX/api/XXX',
        method: 'GET',
        status: 200,
        response: { data: [mockData] },
      },
    ],
  },

Thanks for help.

Suggestion: Refresh component when pausing/activating requests mocking.

Hi!

Could it be possible to add an option so that, when pausing/activating requests mocking, the story is refreshed.
It would be very convenient for a React component that implement such hooks:

const ResourceDisplayer = () => {
  const [resources, setResources] = useState<?Array<Resource>>(null);
  const [displayError, setDisplayError] = useState<boolean>(false);

  const fetchResources = useCallback(async () => {
    try {
      setDisplayError(false);
      const resources = await getResources();
      setResources(resources);
    } catch (err) {
      console.log(`Error when fetching resources: ${err}`);
      setDisplayError(true);
    }
  }, []);

  useEffect(
    () => {
      fetchResources();
    },
    [fetchResources]
  );
  return ( ... )
}

Global mock decorator

Is there a way to write a single storybook-addon-mock decorator (maybe in .storybook/preview.js) that applies to all of my stories?

I tried this in .storybook/preview.js and it did not work for me:

import withMock from "storybook-addon-mock";

const ApiRequestMock = ({ children }) => {
  return <>{children}</>;
};
const BoundApiRequestMock= ApiRequestMock.bind({});
BoundApiRequestMock.parameters = {
  mockData: [
    {
      url: "/api/my_endpoint",
      method: "GET",
      status: 200,
      response: {
        data: "my data"
      }
    }
  ]
};

export const decorators = [
  withMock,
  (Story, context) => (
    <BoundApiRequestMock>
      <Story context={context} />
    </BoundApiRequestMock>
  )
];

`requestPath matched false`

Using this configuration:

WithoutSession.parameters = {
	mockData: [
		{
			url: "http://localhost:6006/api/auth/session",
			method: "GET",
			status: 200,
			response: {},
		},
		{
			url: "localhost:6006/api/auth/session",
			method: "GET",
			status: 200,
			response: {},
		},
        ]
}

I always get this error:

image

The requests don't get mocked and are sent out

Seems like the urls are not mocked correctly

Non-Mock Requests Missing Headers

I have stories that do not use this addon which stopped working after I installed it. It appears the headers are being stripped when going to the destination. These are headless CMS requests and I don't want to mock them.

If someone can point me to the passthrough portion of the code, I'd be glad to try and submit a PR.

Ignore url params (query string)

I've a scenario where I need generate dynamic url params, like:

?person[0][name]=John+Doe&person[1][name]=Hello+World

When I set the mockData I need mock the parameters too. That way I've got an error when the mock is different from the url request: net::ERR_NAME_NOT_RESOLVED.

A solution would be to create an option to disable the query string check.

response.data returned as response.data.data

Great plugin, but I have an issue, here is my mock data:
mockData: [ { url: 'https://team?search=&detail=light', method: 'GET', status: 200, response: { data: [ { id: '7238d186-7cbb-4129-b100-804302ae8c89', email: '[email protected]', first_name: 'Lea', last_name: 'Thompson' }, { id: '577bffd9-88a6-432b-adbe-195ed46ef6f3', email: '[email protected]', first_name: 'Cyndi', last_name: 'Lauper' }, { id: 'c47a6c3e-9d9a-4596-b183-68bd4eaf4881', email: '[email protected]', first_name: 'Tom', last_name: 'Cruise' } ] } } ]

but it its being returned as response.data.data

Relative url paths fallback to localhost/...

Hello! Happy 2022!

I'm having an issue when using addon-mock on github pages. I'll try to explain here the situation;

  • Local storybooks is running on http://localhost:7007 (default)
  • Production storybooks is running on https://storybooks.mycompany.com under github pages

When doing stuff on local, the mock works fine because the API call is made to localhost:3000. So this works on local:

   //...
   mockData: [
      {
        url: `${window.location.origin}/api/endpoint-foo`, // Mock panel shows: http://localhost:7007/api/endpoint-foo as url
        method: 'POST',
        status: 200,
        response: {
          foo: 'bar'
        },
      },
   ]
   //...

First issue I see is that the port is ignored. The request to http://localhost:3000 is being mocked even though it should mock the http://localhost:7007, which is confusing after seeing this add-on's code, but it works.

The other issue is regarding the relative urls.
I found some issues on the code that, following my line of thought, leave some questions unanswered;

https://github.com/nutboltu/storybook-addon-mock/blob/master/src/utils/url.test.js#L17
this tests is saying that given a relative path it will always expect localhost to be the origin? So is not possible to host storybook's elsewhere and mock requests.

Then here https://github.com/nutboltu/storybook-addon-mock/blob/master/src/utils/url.js#L3
it makes visible that it only accepts http as protocol, otherwise it will try to mock http://localhost ...
this two behaviors makes some noise for me and I'd like to know how to write my mocks to overcome these difficulties.
Or in the case we need to apply a patch I'll try to create a PR for you with a potential fix if it is welcomed!

Regards!

Problem with mock change and play/pause button

I was facing a problem with mock change on storybook page ("mock request" addon tab), then digging into the code I've found this:

In this file the parameters are passed separated.

https://github.com/nutboltu/storybook-addon-mock/blob/e239420f1971a0e1fd5a77ededce4896978d9a91/src/manager.js#L21-L27

And here the parameters are received in the same way.

https://github.com/nutboltu/storybook-addon-mock/blob/e239420f1971a0e1fd5a77ededce4896978d9a91/src/index.js#L19-L22

But debugging I realized that the channel.on receive only one parameter. I guess this behavior maybe occur only in my storybook version: 5.3.19. Locally I've change those files and worked well:

/src/manager.js

    const onSkip = (item) => {
        emit(ADDONS_MOCK_UPDATE_DATA, {
            item,
            key: 'skip',
            value: !item.skip,
        });
    };

    const onRequestChange = (item, key, value) => {
        emit(ADDONS_MOCK_UPDATE_DATA, {
            item,
            key,
            value,
        });
    };

/src/index.js

        channel.on(ADDONS_MOCK_UPDATE_DATA, ({ item, key, value }) => {
            faker.update(item, key, value);
            channel.emit(ADDONS_MOCK_SEND_DATA, faker.getRequests());
        });

My concern is my changes affect others storybook versions.

TypeError: Failed to construct 'URL': Invalid URL

I found an error after upgrading storybook-addon-mock to v2.0.0.

Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL

スクリーンショット 2021-11-30 16 19 19

I passed following object as parameters:

{
  mockData: [
    {
      url: '/news/unread_count',
      method: 'GET',
      status: 200,
      response: { unreadCount: 100 },
    },
  ],
}

This worked before upgrading the version. (was v1.7.0)

memo

  • I tried to change the url to http://localhost:3000/news/unread_count but the same error is thrown.

mockData.response presumes a JSON response body

See here: https://github.com/nutboltu/storybook-addon-mock/blob/e239420f1971a0e1fd5a77ededce4896978d9a91/src/components/RequestItem/index.js#L142

Since response must be either an object or an array it's basically presuming a JSON response body.

That makes it impossible to mock a data stream, SOAP, or other types of APIs that aren't strictly REST+JSON.

Would you be open to accepting a PR to also allow a string type for response so that it can work with a wider range of APIs?

thank you -- this worked right away with no trouble (storybook, urql, vue3, graphql)

thank you! I initially tried using an urql-specific addon and there were many issues and it didn't work. I really like that its possible to generate dynamically created responses later if I need those

export const NORMAL = Template.bind({});
NORMAL.decorators = [ vueRouter() ];
NORMAL.parameters = {
  mockData: [{
    url: endpointUrl,
    method: 'POST',
    status: 200,
    response: {
      data: {
        getSelf: {
          id: 'id',
          name: 'name',
          email: 'email'
        }
      }
    }
  }]
};

Breaks when using `XMLHttpRequest` directly

I am using this pattern, for lightweight and compatibility reasons:

const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
  resolve(xhr.response);
};
xhr.send();

When using storybook-addon-mock, xhr.response is a JSON object, while the native version returns a string - that I later run through JSON.parse.

I understand that my use-case is the large minority, as there is very little reason to be using both XMLHttpRequest and Storybook. I won't extend the reasons I am using XMLHttpRequest instead of fetch - for example -, but I wanted to report my issue.

If someone has a similar issue, here is a quick dirty fix:

const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
  resolve(
    typeof xhr.response === "string"
      ? xhr.response
      : JSON.stringify(xhr.response)
  );
};
xhr.send();

Not able to have mocked story and normal story

I have a nextjs storybook project setup, with a laravel backend for authentication.

On every page I request the authenticated user: http://127.0.0.1:8000/api/user

This works perfect when I'm loggedin, but it is anyoning having to login everytime I start the project, so I mock the request. What also works perfect.

But my problem is, i'd like to have 2 stories:

  1. Non mocked, so i can test the login flow
  2. Mocked, so I can easily test the page i'm developing

So the strange thing, i have is the moment I import withMock my non mocked story doesn't work anymore, and the request above gets a 302 not found.

Here you can see the request works fine:
Screenshot 2022-05-30 at 08 56 51

Now I add line:
import withMock from 'storybook-addon-mock'

And now the request breaks:
Screenshot 2022-05-30 at 08 57 03

Do you have any idea what this can be? I tried so many things, also in my backend API, but nothing helps.

Response text() returns object instead of text

Description

I'm having an issue with the faked response type. Specifically, the text() and json() methods both return the response object, when Response.text() should return a string to be compliant with the API.

This is a problem when using this library with RTK Query, for example. For some reason, they read the text() response and parse it to JSON themselves instead of calling json() directly. Can't say I get why, but it's technically valid.
https://github.com/reduxjs/redux-toolkit/blob/master/packages/toolkit/src/query/fetchBaseQuery.ts#L57

I assume there are also other libraries out there that read responses in the same way. This is just the one that I happened to run into.

Proposed Solution

The problem is created by this line.
https://github.com/nutboltu/storybook-addon-mock/blob/master/src/utils/response.js#L13

Calling the 3rd argument responseText seems to be misleading, since as far as I can tell it will always be an object. Just to be careful, though, I believe that the code should be:

this.text = () => Promise.resolve(typeof responseText === "string" ? responseText : JSON.stringify(responseText));
this.json = () => Promise.resolve(responseText);

Let me know if you agree on the solution and I can open up a quick PR.

ChainAlert: npm package release (2.2.0) has no matching tag in this repo

Dear storybook-addon-mock maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (2.2.0) of storybook-addon-mock was published without a matching tag in this repo.

Our service monitors the open-source ecosystem and informs popular packages' owners in case of potentially harmful activity.
If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

Is this expected to work with storyshots?

I'm using this with my storybook and all works fine but when I run with storyshots via jest, it's trying to hit a real server. Is the mocking expected to work with StoryShots?

withMock returning wrong mock when similar url structure

I'm trying to mock a server search by user name, which would be used in an autocomplete feature.

Eg.: /api/users?name_like=a returns users starting with A; and, /api/users?name_like=b returns starting with B.

However, mocks always return the last mock when trying to mock this scenario. The panel Mock Request also doesn't look good, only displaying the last mock.

image

Here is a piece of code to reproduce:

import { ComponentStory, ComponentMeta } from '@storybook/react';
import { useEffect, useState } from 'react';
import withMock from 'storybook-addon-mock';
import { fetch } from '../../Api/fetcher';

const ApiRequestExample = ({ url }: { url: string }) => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      console.log("fetching url: " + url);
      
      setData(await fetch(url));
    };

    fetchData();
  }, []);

  return <><b>{url}</b><pre>{JSON.stringify(data)}</pre></>;
};

export default {
  component: ApiRequestExample,
  title: 'Mock/Missing Mocks',
  decorators: [withMock],
  parameters: {
    mockData: [
      {
        url: '/api/users?name_like=a',
        method: 'GET',
        status: 200,
        response: {
          content: [{ name: 'Allison', age: 32 }, { name: 'Amelia', age: 25 }, { name: 'Amber', age: 19 }], page: 1, size: 3},
      },
      {
        url: '/api/users?name_like=b',
        method: 'GET',
        status: 200,
        response: {
          content: [{ name: 'Betty', age: 22 }, { name: 'Bruce', age: 41 }, { name: 'Bryan', age: 37 }], page: 1, size: 3},
      },
    ],
  },
} as ComponentMeta<typeof ApiRequestExample>;

const Template: ComponentStory<typeof ApiRequestExample> = (prms) => {
  return <ApiRequestExample {...prms} />;
};

export const UsersWithA = Template.bind({});
UsersWithA.args = { url: '/api/users?name_like=a' };

export const UsersWithB = Template.bind({});
UsersWithB.args = { url: '/api/users?name_like=b' };

Missing POST body when sending real requests instead of mocks

Thank you for the great plugin!

It seems that the plugin will catch all requests in storybook once it's registered, no matter if it's configured in a specific story.
In case when we have also stories using real endpoints (XMLHttpRequest), the POST body is ignored by the plugin.

requestMap is empty if using mdx based custom docs

I m facing a strange issue where using a custom mdx doc fails to run the faker on the requests. As soon as I remove the custom doc, it continues to work as expected.

Example code

export default {
  title: 'Example/Login',
  component: Login,
  parameters: {
    docs: {
      page: mdx,
    },
  },
  decorators: [withMock],
};

From the above if I remove the docs param, the faker continues to work as expected

export default {
  title: 'Example/Login',
  component: Login,
  parameters: {},
  decorators: [withMock],
};

My mock data is set on the story template itself

export const Login = () => {
  <SomeWrapper>
    <ImportedComponent />
  </SomeWrapper>
}

Login.parameters = {
    mockData: [
    ...
    ]
}

Can you please advise what I could be missing?

Incompatibility with RTKQ

I use RTKQ and noticed that response payloads set in storybook-addon-mock are returned as undefined in RTKQ.

I debugged the issue and found that this line in RTKQ is the culprit:
image

As you can see, RTKQ assumes the response to be a string, since it is an object it does nothing and returns undefined.
The obvious solution was then to just stringify my response
mockData: [ { url: "myUrl", method: "GET", status: 200, delay: 500, response: JSON.stringify(responseObj) } ]

But storybook-addon-mock doesn't like that.

Would it be possible to add a flag like "stringifyResponse" which causes the response to be stringified before being sent as response?

Mocked fetch response cannot dynamically change HTTP status, status text or headers

When mocking fetch responses, we should have full dynamic control over all aspects of the Response object, including:

  • body
  • status
  • statusText
  • headers

Currently, we only have this:

  • body: static object or dynamic based on request (when setting the mocked response to a function)
  • status: static number; no ability to dynamically change it based on request
  • statusText: no control at all
  • headers: no control at all

Example use case

I have a fetch endpoint that various authentication tasks and they all use the same URL; the endpoint returns different data, status codes and headers depending on the request body.

In one story, I have a page component that needs to have the client credential request respond with HTTP 200 immediately followed by another request to the same endpoint that should respond with HTTP 500 (mocking a user validation error).

Does @emotion/styled need to be a dependency?

It seems as though styled is used in 4 places in the source code. Is it possible to drop this dependency and style those components with another CSS technology that doesn't need a large CSS-in-JS library?

Unexpected console output

The package unconditionally outputs the following:

console.log
      this.requestMap[key] {
        url: '...',
        response: { ... },
        ignoreParams: true,
        path: '...',
        searchParamKeys: [],
        method: 'GET',
        status: 200,
        delay: 0,
        skip: false
      } key ...

      at Faker.matchMock (node_modules/storybook-addon-mock/dist/utils/faker.js:104:17)

    console.log
      requestPath ... matched false

      at Faker.matchMock (node_modules/storybook-addon-mock/dist/utils/faker.js:105:17)

The package downloaded from the npm contains the following code:

        console.log('this.requestMap[key]', _this.requestMap[key], 'key', key);
        console.log('requestPath', requestPath, 'matched', (0, _pathToRegexp.match)(requestPath)(path));

I've checked the source code, there's no output there. I've cloned the repo and built it locally, there's no output as well.
Did it appear by mistake, or for a purpose?
Thanks in advance.

React v18 `npm install` package dependency compatibility

Hi there!

My project has recently upgraded to React v18 and I am currently running into a ERESOLVE unable to resolve dependency tree error when I try to npm install storybook-addon-mock. It does work if I add the --legacy-peer-deps flag, but ideally I'd like to avoid using it.

image

Any help would be greatly appreciated!

[bug] Global http requests

Hi, whenever I do a http request from a component that does not use this plugin in its story, then the response fails

something like this fails :

const response = await fetch(${url}?r=${Math.random()}).then(response => response.blob())

the stack errors said it was faker.js from this module, so I would prefer an option from parameters to enable this instead of being registered globally and preventing http requests to success

Error when fetch's init argument isn't set

The second argument of fetch() is optional: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#syntax

This addon's mocked Request object tries to access the options.method property without checking that options is set, and so throws an error if options is undefined.

export function Request(input, options) {
    if (typeof input === 'object') {
        this.method = options.method || input.method || 'GET'; // fails if `options` isn't set
        this.url = input.url;
    } else {
        this.method = options.method || 'GET'; // also fails
        this.url = input;
    }
}

allow some requests to pass through?

I'm using graphql and I need to only mock a few requests while letting the rest hit the server, so for example:

/graphql - with specific body should be mocked
/graphql - all the rest should not be mocked

can we add some kind of matcher for the body to allow to only mock some requests and allow others to pass through?

Display modernized example

The available example is written using an old Storybook API. Is it possible to give an example using modern API. Eg using:

export default {
  title: 'Card',
  component: Card,
  argTypes: {},
}

const Template = args => <Card {...args} />

export const Default = Template.bind({})
Default.args = {}

and so on?

Response customization based on request data

Hi there,

Great addon -- I've been using it to mock a couple of views for the design team to work on making pretty before the application is ready to go live.

I have a question though, would it be possible to return different mock data depending on the request? For example, I have a /data endpoint but depending on what is passed in the JSON request, it returns a different dataset response.

Thanks!

[Bug] Unexpected MODIFIER at 35, expected END

I'm trying to mock, but i got error

Unexpected MODIFIER at 35, expected END

Call Stack
 mustConsume
  vendors~main.iframe.bundle.js:1634:15
 parse
  vendors~main.iframe.bundle.js:1693:20
 stringToRegexp
  vendors~main.iframe.bundle.js:1846:27
 pathToRegexp
  vendors~main.iframe.bundle.js:1919:12
 match
  vendors~main.iframe.bundle.js:1766:26
 Faker/<
  vendors~main.iframe.bundle.js:2101:37
 Faker/<
  vendors~main.iframe.bundle.js:2132:26
 send/<
  vendors~main.iframe.bundle.js:1482:33

Here the code :

import { SectorBlueFilter } from 'core/components/BlueFilter/SectorBlueFilter'
import withMock from 'storybook-addon-mock'

export default {
  title: 'Ui/Form/sectorbluefilter/SectorBlueFilter',
  component: SectorBlueFilter,
  decorators: [withMock]
}

export const Default = args => <SectorBlueFilter {...args} />

Default.args = {}
Default.argTypes = {
  onChangeOption: { action: 'site / sector changed' }
}
Default.parameters = {
  mockData: [
    {
      url: 'http://localhost:10510/brain/sites/sectors?all=true',
      method: 'GET',
      status: 200,
      response: [
        {
          id: 8,
          name: 'Demo'
        }
      ]
    }
  ]
}

Ambiguous warning message shown on console

Hello. I notice that several warning messages unfortunately come with the application of this addon, and they even appear when the example storybook in this repository is started on my local. They can be reproduced once you

  • clone the repo
  • run yarn && yarn storybook
  • open / reload for http://localhost:6006/?path=/story/storybook-addon-mock-request--mocking-fetch-and-axios

Screenshot 2021-08-12 at 5 27 16 PM
Screenshot 2021-08-12 at 5 27 30 PM

It is quite annoying to have them in the development process, even when the mocking works perfectly well. Are there any possible fixes able to come soon?

Anyway thanks for your great work.

Remove Mock request panel on stories that do not use it

HI there,

Thank you for your work on this addon!

Here is my code:

export default {
  title: 'ProfileDetails',
  component: ProfileDetails,
  decorators: [paperDecorator, muiDecorator],
  argTypes: {
    profile: {
      control: { type: 'radio' },
      options: ['Complete profile', 'Without username nor bio'],
      defaultValue: 'Complete profile',
      mapping: {
        'Complete profile': completeProfile,
        'Without username nor bio': incompleteProfile,
      },
    },
  },
};

const apiDataServerSideError = {
  mockData: [
    {
      url: 'https://url.to.mock',
      method: 'GET',
      status: 500,
      response: { data: 'status' },
    },
  ],
};

export const MyProfile = (args: ArgsTypes) => (
  <ProfileDetails {...args} />
);
export const MyProfileWithAchievementLoadingError = (args: ArgsTypes) => (
  <ProfileDetails {...args} />
);
MyProfileWithAchievementLoadingError.decorators = [withMock];
MyProfileWithAchievementLoadingError.parameters = apiDataServerSideError;

Note: This is the unique part of my code where I use withMock.

Here is what happens to me:

bug_panel_storybook_addon_mock.mov

I feel like the panel, and the mock, should disappear when switching to a component that is not decorated with withMock.

bug: Having addon-mock installed breaks pass-through requests

Hello team,

I'm having an issue where stories featuring an embedded video player (with Javascript) are not correctly loading.

I've updated to 2.4.1, as I was previously having an issue with the headers not being passed through correctly.

The stories I'm having an issue with do not have the "withMock" decorator imported or used, but other stories (that don't use the player) are using it.

If I comment out all the

import withMock from 'storybook-addon-mock';

and

decorators: [withMock],

The video player again works perfectly.

Interesting tidbit: even with the mocking enabled, it works in Safari.

I'm using 1.39.120 Chromium: 102.0.5005.99 (Official Build) (x86_64)

The 'symptom" is that the player loads forever, it doesn't stop buffering after the first 9 segments, it continues sending network requests for more data... Weird behavior, but probably just a result of something being 'lost in translation' between their library and the server.

usage with swr not working

Hey, this looks like an awesome utility!

This also works out of the box when using fetch directly, however it appears to not work with my usage of swr.

What would be the best approach to debug this and see why this is not working?

Thanks in advance!

Some snippets for reference:

// the api call does not get intercepted
 const {
    channels,
    isLoading,
    isError,
    mutate: mutateChannels,
  } = useChannels();

// this api call does get intercepted
  useEffect(() => {
    async function getChannels() {
      const response = await fetch("http://localhost:3030/channels");
      console.log(await response.json());
    }
    getChannels();
  }, []);

the useChannels hook:

const channelsFetcher = () => {
  return client
    .service("channels")
    .find()
    .then((res) => {
      return res.data;
    });
};

export default function useChannels() {
  const { data, error, mutate } = useSWR<Channel[]>(
    "channels",
    channelsFetcher
  );

  return {
    channels: data,
    isLoading: !error && !data,
    isError: error,
    mutate: mutate,
  };
}

Wildcards in url?

Thanks for a great addon!

I'm trying to dig up whether I can use some wildcard features in the url (or "match strategies")... any pointers or straight no?

My problem is that I have a /api/foos url that's paginated like this /api/foos?skip=0&limit=20&dir=desc&sort=blabla which is a bit flaky and tedious in my simple Storybook test where I just wanna control what's returned, no matter the querystring. So being able to do `url: "/api/foos" somehow and still match it would be nice.

Thanks!

Progress events on upload

It appears that mock-xmlhttprequest supports emitting progress events on mocked upload requests (via the .uploadProgress(number) method).
Currently, a full 100% progress event is emitted at the end of the response. If a delay is specified, would it be possible to emit a few progress events at regular intervals before the call to .respond() so we can simulate progress events during a large file upload?

faker.js URL parsing

Hi! Thanks for the quick merge, and I see there's more strictness on valid URLs. The issue being caused now is that hot module reload is sending just chunk.kdas83138rj3.js, rather than the fully qualified http://localhost:6006/chunk.kdas8312.js, which is then going straight into new URL(generated) and being rejected. Everything is working correctly if the withMock decorator is removed. It's also (potentially) a regression from 1.0.0 which allowed url: '/api/v2/xxx' instead of now requiring url: 'http://localhost:6006/api/v2/xxx'. That's not a huge issue of course though as it can be easily resolved locally

I've pasted this into /dist/utils/faker.js and it's working correctly for me with it in place:

var withOrigin = rawUrl.indexOf('/') === 0 ? `${window.location.origin}${rawUrl}`
        : rawUrl.indexOf('http') !== 0 ? `${window.location.origin}/${rawUrl}`
        : rawUrl

      var url = new URL(withOrigin);
      var searchParamKeys = [];`

Query parameters

First of all, thanks for your addon.

I'm using your addon for a few days, and I have a scenario where I pass some query parameters based on select options. So depending on what option is selected I'll pass a different parameter to the query string. That way I'll need to set many different items in the mockData to the same API url.

I believe that the addon should ignore the query string passed. Or at least have an option to not take the query string passed into account.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.