Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active October 21, 2024 17:55
Show Gist options
  • Save cowboy/44ae5deed5d04d2cf28f2087fde2c89c to your computer and use it in GitHub Desktop.
Save cowboy/44ae5deed5d04d2cf28f2087fde2c89c to your computer and use it in GitHub Desktop.
axios mocking via interceptors
import axios from 'axios'
let mockingEnabled = false
const mocks = {}
export function addMock(url, data) {
mocks[url] = data
}
export function enableMocking(state) {
mockingEnabled = state
}
const isUrlMocked = url => url in mocks
const getMockError = config => {
const mockError = new Error()
mockError.mockData = mocks[config.url]
mockError.config = config
return Promise.reject(mockError)
}
const isMockError = error => Boolean(error.mockData)
const getMockResponse = mockError => {
const {mockData, config} = mockError
// Handle mocked error (any non-2xx status code)
if (mockData.status && String(mockData.status)[0] !== '2') {
const err = new Error(mockData.message || 'mock error')
err.code = mockData.status
return Promise.reject(err)
}
// Handle mocked success
return Promise.resolve(Object.assign({
data: {},
status: 200,
statusText: 'OK',
headers: {},
config,
isMock: true
}, mockData))
}
// Add a request interceptor
axios.interceptors.request.use(config => {
if (mockingEnabled && isUrlMocked(config.url)) {
console.log('axios mocking ' + config.url)
return getMockError(config)
}
return config
}, error => Promise.reject(error))
// Add a response interceptor
axios.interceptors.response.use(response => response, error => {
if (isMockError(error)) {
return getMockResponse(error)
}
return Promise.reject(error)
})
import axios from 'axios'
import {addMock, enableMocking} from './mock-axios'
addMock('https://dog.ceo/api/breeds/list/all', {data: {mock: 'dogs'}})
addMock('https://dog.ceo/404-page', {status: 404, message: 'whoops'})
enableMocking(true)
// mocked
let result = await axios.get('https://dog.ceo/api/breeds/list/all')
console.log(1, result)
try {
result = await axios.get('https://dog.ceo/404-page')
} catch (err) {
console.log(2, err)
}
// not mocked
result = await axios.get('https://dog.ceo/api/breeds/list/all?foo=1')
console.log(3, result)
try {
result = await axios.get('https://dog.ceo/unhandled-404')
} catch (err) {
console.log(4, err)
}
@naholyr
Copy link

naholyr commented Sep 12, 2019

Very well done

@okovalov
Copy link

Really nice!

@el0911
Copy link

el0911 commented May 7, 2021

Lol i legit clapped when i saw this like i can kiss ur feat so obvious and amazing at the same time

@gaboAcosta
Copy link

Nice job cowboy!

@jeffreesta
Copy link

This module provides a way to mock Axios requests and responses for testing Spend Elon Musk Money or development purposes by intercepting requests and responses and returning mock data instead of making actual HTTP requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment