5

Been trying to use storybook with my VueJS project and Im stuck with mocking api calls. I tried using axios-mock-adapter without luck.

My storybook file code is:

import { storiesOf } from '@storybook/vue';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean } from '@storybook/addon-knobs';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import fileUpload from './fileUpload.vue';

const mock = new MockAdapter(axios);

mock
  .onPost('https://s3.amazonaws.com')
  .reply(200, []);

storiesOf('Common|File CSV Upload', module)
  .addDecorator(withKnobs)
  .add('Default', () => ({
    components: { fileUpload },
    data: () => ({
    }),
    template: ` 
        <v-flex>
            <file-upload></file-upload>
       </v-flex>`,
    methods: {
      action: action('file upload'),
    },
  }));

Am I using it right?

badigard
  • 820
  • 2
  • 10
  • 22

1 Answers1

0

My strong recommendation is to use storybook-addon-mock for mocking (axios) API calls in Storybook.

It is nicley integrated into Storybook, setup in the different stories is easy and the data can be alteresd in the corresponding panel.

These 4 steps are needed:

  1. Add the additional dependency: yarn add storybook-addon-mock

  2. adapt the config and add in .storybook/main.js:

module.exports = {
  addons: [
    ...
    'storybook-addon-mock',
  ],
  1. configure the behaviour and add mock data for general/ repeating API calls in .storybook/preview.js. These are mocks that will be available in every story.
export const parameters: Parameters = {
  mockAddonConfigs: {
    globalMockData: [
      {
        url: 'api/token',
        method: 'POST',
        status: 200,
        response: () => '1234567abcdefg',
      },
    ],
    refreshStoryOnUpdate: true, // This re-render the story if there's any data changes
    // disable: true, // This disables the panel from all the stories
  }
  1. in your story file add:
export default {
  title: 'components/myComponentName',
  component: MyComponent,
  parameters: {
    mockData: [
      {
        url: '/api/myendpoint/',
        method: 'GET',
        status: 200,
        delay: 500,
        response: () => 'some content',
      },
      {
        url: '/api/myendpoint/',
        method: 'POST',
        status: 200,
        delay: 1000,
        response: {
          data: 'some response',
        },
      },
    ],
  },

Hint: Have a look into the different responses - function, string, etc to match them with the real response. There can be a pitfall with the data entry, that can be avoided with response: () => 'some content'

cwillinx
  • 537
  • 2
  • 13