Search code examples
vue.jsaxiossinonstubstorybook

Stub axios twice in storybook


I have several components using Axios calls, I am trying to "stub" those functions, however, I receive the following error on the storybook "Attempted to wrap get which is already wrapped".

I wonder if there's a way to define several times a stub because I tried using sinon.reset() at the end of each compXX.stories.js but it does not work.

Here is some of the code:

comp123.stories.js

import VueCustomElement from 'vue-custom-element';
import Vue from 'vue';
import sinon from 'sinon';
import axios from 'axios';
import * as rawJSON from './123-response.json';
import comp123 from 'comp123';
Vue.use(VueCustomElement);

const aStub = sinon.stub(axios, 'get').resolves(Promise.resolve(
    rawJSON.default
));

export default {
  title: '123 component',
  component: comp123,
  decorators: [withA11y],
};

export const Base = () => ({
  components: {comp123},
  template: `<div class="comp123"> ...component123
  </div>
  `,
});

comp345.sories.js

import VueCustomElement from 'vue-custom-element';
import Vue from 'vue';
import sinon from 'sinon';
import axios from 'axios';
import * as 345response from './345-response.json';
import comp345 from 'comp345';
Vue.use(VueCustomElement);

    const aStub = sinon.stub(axios, 'get').resolves(Promise.resolve(
        345response.default
    ));

    export default {
      title: '345 component',
      component: comp345,
      decorators: [withA11y],
    };

    export const Base = () => ({
      components: {comp345},
      template: `<div class="comp345"> ...component345
      </div>
      `,
    });

Solution

  • A partner got it solved by adding a middleware.js file in the .storybook folder, so we don't mock data, we get the actual data from a "local server" in this case and can be changed depending on the server you are on.

    PD: I am using AEM. The server has to be on and logged in.

        const { createProxyMiddleware } = require('http-proxy-middleware');
    
       module.exports = function expressMiddleware (app) {
       app.use('/services', createProxyMiddleware({
         target: 'http://localhost:4502/services',
         changeOrigin: true,
         pathRewrite: {
          '^/services': '',
         },
      }))