Mock api calls from Storybook

Alan P. picture Alan P. · Mar 6, 2018 · Viewed 9.2k times · Source

Does axios-mock-adapter only work on requests made with axios?

I have written a component that POSTs to an API (using vanilla XHR, not axios). I'm testing it in Storybook and want to intercept those POST requests since the endpoint doesn't exist yet:

import React from "react"
import { storiesOf } from "@kadira/storybook"
import MyComponent from "./MyComponent"
import axios from "axios"
import MockAdapter from "axios-mock-adapter"

var mock = new MockAdapter(axios)

storiesOf("My Component", module).addWithInfo(
  "Simulator",
  () => {
    mock.onPost().reply(500)
    return <MyComponent />
  },
  {}
)

My component still is trying to hit the API endpoint and I am getting a 404 response - not the expected 500 response.

Does axios-mock-adapter only work on requests made with axios? Does the mock call have to be inside MyComponent?

Thanks.

Answer

Vance Faulkner picture Vance Faulkner · Feb 7, 2019

xhr-mock should work for local testing where you probably don't want to make requests across the internet.

Outside of testing, if you are waiting on the real endpoints to be built you could use Mock/it (https://mockit.io) in development. You can claim your own dedicated subdomain and swap it out later for the real one. Disclaimer: this is a side project I recently released and would love any feedback on it!