Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock api calls from Storybook

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.

like image 877
Alan P. Avatar asked Mar 06 '18 00:03

Alan P.


People also ask

What is storybook addon essentials?

A major strength of Storybook are addons that extend Storybook's UI and behavior. Storybook ships by default with a set of “essential” addons that add to the initial user experience. There are many third-party addons as well as “official” addons developed by the Storybook core team.

What does mock service worker do?

Mock Service Worker is an API mocking library that uses Service Worker API to intercept actual requests.


2 Answers

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!

like image 57
Vance Faulkner Avatar answered Sep 19 '22 13:09

Vance Faulkner


You can use xhr-mock instead of axios-mock-adapter.

Utility for mocking XMLHttpRequest.

Great for testing. Great for prototyping while your backend is still being built.

Works in NodeJS and in the browser. Is compatible with Axios, jQuery, Superagent >and probably every other library built on XMLHttpRequest

import mock from 'xhr-mock';

storiesOf("My Component", module).addWithInfo("Simulator",
() => {

    mock.post('', {
      status: 500,
      body: '{}'
    });

    return <MyComponent />
    },
    {}
)

Additionaly you need to add jquery script in preview-head.html file in storybook

1) https://www.npmjs.com/package/xhr-mock

like image 29
michalbegej Avatar answered Sep 19 '22 13:09

michalbegej