Mock axios instance+interceptor with axios-mock-adapter

node v7.10.1
version: 4.0.0
endpointsharetweet
// Create axios instance const axios = require('axios'); require('promise.prototype.finally').shim(); const api = axios.create({ baseURL: '/api/', timeout: 2500, headers: { Accept: 'application/json' }, });
// Add interceptor const localStorage = require('localStorage'); const TOKEN = 'ABC'; localStorage.setItem('jwt', TOKEN); api.interceptors.request.use((config) => { const token = localStorage.getItem('jwt'); const tokenInAxios = api.defaults.headers.common.Authorization; if (token && !tokenInAxios) { api.defaults.headers.common.Authorization = token; } return config; });
// Define our store const mobx = require('mobx'); const mobxUtils = require('mobx-utils'); const Store = function() { mobx.extendObservable(this, { versions: [], getVersions: mobx.action(() => { const promise = api .get('/versions') .then(resp => (this.versions.replace(resp.data))); return mobxUtils.fromPromise(promise); }) }) return this; }
// Execute test on instance const MockAdapter = require('axios-mock-adapter'); const assert = require('assert'); const mock = new MockAdapter(api); const versions= [{ id: 1, desc: 'v1' }, { id: 2, desc: 'v2' }]; mock.onGet('/versions').reply(200, versions); const store = new Store(); const result = store.getVersions(); mobxUtils.whenWithTimeout( () => result.state === mobxUtils.FULFILLED, () => { assert.deepEqual(mobx.toJS(store.versions), versions, 'Store is updated.'); assert.equal( api.defaults.headers.common.Authorization, TOKEN, 'default token is updated' ); mock.reset(); mock.restore(); }, 600, () => { throw new Error(`${result.state} state is not valid`, result.value); mock.reset(); mock.restore(); }, );
Loading…

no comments

    sign in to comment