nuxt-community / axios-module

Secure and easy axios integration for Nuxt 2
https://axios.nuxtjs.org
MIT License
1.19k stars 246 forks source link

Mock axios on Storybook #532

Open bissolli opened 3 years ago

bissolli commented 3 years ago

Hey guys, I was wondering how can I mock the axios instance of this module on Storybook. Has anyone accomplished it?

On a plain Vue project usually I mock the axios instance before mounting the component like this:

import { Args, StoryContext } from '@storybook/addons'
import MockAxiosAdapter from 'axios-mock-adapter'
import axios from "axios"

// Main problem using @nuxjs/axios is that I can't get
// the axios instance used by the package
const mockAxios = new MockAxiosAdapter(axios)

export default {
  title: 'MyComponent',
  component: MyComponent,
  argTypes: {
    // This setup is just to separate PROPS and HTTP Mocks in the
    // control tab
    payment: {
      table: {
        category: 'HTTP Mocks',
      },
    },
  },
}

// This is a factory to get a payment fixture with faker.js
const mockPayment = PaymentFactory.build()

mockAxios
  .onGet(`/whatever-api-endpoint/${mockPayment.id}`)
  .reply(200, mockPayment)

const Template = (_: Args, { argTypes }: StoryContext) => ({
  props: Object.keys(argTypes),
  components: { MyComponent },
  template: `<my-component />`,
})

export const Component = Template.bind({})
Component.args = {
  // Props
  paymentId: mockPayment.id,

  // HTTP Mocks
  payment: mockPayment,
}

My main problem is how to get the axios instance from the package to be able to mock it here const mockAxios = new MockAxiosAdapter(axios)

Any clue?! I am very curious to see how you guys mock HTTP requests on your stories as well - I am open to know new approaches =)

NOTE: I tried mocking in the setup method of my Template, but is doesn't work well when you have useAsync or useFetch.

JoseOrtiz commented 2 years ago

What I did is move the creation of the mock inside the Template definition, an use this.$axios

const Template = (_: Args, { argTypes }: StoryContext) => ({
  props: Object.keys(argTypes),
  created() {
    const mockAxios = new MockAxiosAdapter(this.$axios);
    mockAxios.onGet(`/whatever-api-endpoint/${mockPayment.id}`).reply(200, mockPayment);
  },
  components: { MyComponent },
  template: `<my-component />`,
});