Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
@davestewart

This comment has been minimized.

Copy link

davestewart commented Jul 3, 2018

Thanks for this! Been looking for something like this for ages now.

@fallemand

This comment has been minimized.

Copy link

fallemand commented Apr 18, 2019

Perfect! Thanks.

@naholyr

This comment has been minimized.

Copy link

naholyr commented Sep 12, 2019

Very well done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.