Skip to content

Instantly share code, notes, and snippets.

@muhammadfaizan
Last active March 2, 2022 07:31
Show Gist options
  • Save muhammadfaizan/2d73fb714029838b0ab2de0fe7a461ba to your computer and use it in GitHub Desktop.
Save muhammadfaizan/2d73fb714029838b0ab2de0fe7a461ba to your computer and use it in GitHub Desktop.
Mocking Axios Request
import test from 'ava'
import axios from 'axios'
import axiosMocker from './axios-mock'
import { externalAPI } from '../../services'
import qs from 'query-string'
const { addMock, enableMocking } = axiosMocker(externalAPI.request)
enableMocking(true)
test.serial('test getAccessToken', async t => {
addMock('/oauth/access_token', {
data: {
data: {
access_token: 'mock_access_token',
expires_in: 543524353
}
}
})
const payload = {
code: 'test_code'
}
const accessTokenInterceptor = externalAPI.request.interceptors.request.use(function (config) {
t.is(config.params.client_id, process.env.CLIENT_ID)
t.true(config.params.redirect_uri.endsWith('/api/v1/external-callback'))
t.is(config.params.client_secret, process.env.CLIENT_SECRET)
t.is(config.params.code, payload.code)
t.is(config.method, 'get')
return config
})
await externalAPI.getAccessToken(payload)
.then((resp) => {
t.is(resp.data.access_token, 'mock_access_token')
t.true(typeof resp.data.expires_in === 'number')
})
.catch(err => {
t.fail(err)
return null
})
externalAPI.request.interceptors.request.eject(accessTokenInterceptor)
})
module.exports = (axios) => {
let mockingEnabled = false
const mocks = {}
function addMock (url, data) {
mocks[url] = data
}
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)
})
return {
addMock,
enableMocking
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment