0

I am using MockAdapter with axios to mock api response in storybook

export const defaultAccountMockAPI = () => {
  const mock = new MockAdapter(axiosInstance);

  const defaultAccountDetails = objectKnob('Default Account Details', DefaultAccountDetails);
  mock
    .onGet(
      '/services/api/account/1902124261/account-details',
    )
    .reply(() => {
      return [200, defaultAccountDetails];
    });
};

export const accoutMockAPI = () => {
  const mock = new MockAdapter(axiosInstance);

  const accountDetails = objectKnob('Account Details', AccountDetails);
  mock
    .onGet(
      '/services/api/account/1902124221/account-details',
    )
    .reply(() => {
      return [200, accountDetails];
    });
};

Let's say I have above two methods which mock default account details and account details. The only difference between these two methods is different account id (1902124261/1902124221). I need to show 2 stories based on these 2 different accounts, how I can abstract the mock api method instead of for each story I need to write these duplicated codes(Apart from account id, I also have other parameters which have this issue as well.)

Yang Wang
  • 580
  • 4
  • 14
  • the account Id and the accountdetails object passed in the objectKnob function are the differences both in both functions. What other parameters have this issue? – Oluwafemi Sule Jul 25 '21 at 12:54

1 Answers1

0

The README file of MockAdapter says that its possible to use a regular expression as url.

So with your code it should look like this:

mock
    .onGet(/\/services\/api\/account\/.*?\/account-details/g)
    .reply(() => {
      return [200, accountDetails];
    });

https://github.com/ctimmerm/axios-mock-adapter/blob/59258dd1e78531853c24a4cf2ed002455f66ecbf/README.md?plain=1#L138

admlz635
  • 1,001
  • 1
  • 9
  • 18