Skip to content

Instantly share code, notes, and snippets.

@ademidun
Last active July 20, 2022 12:27
Show Gist options
  • Save ademidun/23d8da9be3235c094c5646f30a58edea to your computer and use it in GitHub Desktop.
Save ademidun/23d8da9be3235c094c5646f30a58edea to your computer and use it in GitHub Desktop.
An example of how to use the axios-mock-adapter
/*
Implementation of https://github.com/ctimmerm/axios-mock-adapter
*/
import Environment from '../Environment';
import ContactsAPI from '../ContactsAPI';
import ContactsQuery1 from './Contacts/ContactsQuery1.json';
import ScholarshipsPreview1 from './Scholarship/ScholarshipsPreview1.json';
import ScholarshipsPreviewOntario1 from './Scholarship/ScholarshipsPreviewOntario1.json';
var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");
export class MockAPI {
static initializeMocks = () => {
console.log("localStorage.getItem('ATILA_MOCK_API_CALLS'", localStorage.getItem('ATILA_MOCK_API_CALLS'));
console.log("ContactsAPI.ContactsQuery", ContactsQuery1);
if (localStorage.getItem('ATILA_MOCK_API_CALLS') !== "true" || Environment.name !== "dev") {
if (localStorage.getItem('MOCK_API_CALLS') === "true") {
console.log(`"User tried to use MOCK_API_CALLS local storage setting in" ${Environment.name} environment.
This feature is only available in 'dev'`)
}
return
}
var mock = new MockAdapter(axios);
mock.onGet(ContactsAPI.contactsApiQueryUrl).reply(200, ContactsQuery1);
mock.onPost(`${Environment.apiUrl}/scholarship-preview/?page=1`).reply(function (config) {
// `config` is the axios config and contains things like the url
// return an array in the form of [status, data, headers]
const requestData = JSON.parse(config.data);
console.log({config, requestData});
let responseData = ScholarshipsPreview1;
if (requestData.searchString && requestData.searchString?.toLowerCase() === "ontario") {
responseData = ScholarshipsPreviewOntario1;
console.log({ScholarshipsPreviewOntario1});
}
return [
200,
responseData,
];
});
}
}
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
/**
* The logic to only allow mocks in dev is alreay handled inside the function initializeMocks()
* Having it here is redundant but it makes it clearer to the user that we only call the mock in dev environments.
*/
if (Environment.name === "dev") {
MockAPI.initializeMocks();
}
render() {
return (
<Router>
<Switch>
<Route
exact
path='/'
component={GoogleAnalyticsTracker(LandingPage)}
/>
</Switch>
</Router>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment