score:91
I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
You can see it the whole example here:
Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
score:0
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
File actions.test.js:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: 'test@test.com',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: 'test@test.com',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
score:5
Look at this
- The function to test
album.js
const fetchAlbum = function () {
return axios
.get("https://jsonplaceholder.typicode.com/albums/2")
.then((response) => {
return response.data;
});
};
- The test
album.test.js
const axios = require("axios");
const { fetchAlbum } = require("../utils.js");
jest.mock("axios");
test("mock axios get function", async () => {
expect.assertions(1);
const album = {
userId: 1,
id: 2,
title: "sunt qui excepturi placeat culpa",
};
const payload = { data: album };
// Now mock axios get method
axios.get = jest.fn().mockResolvedValue(payload);
await expect(fetchAlbum()).resolves.toEqual(album);
});
score:7
I've done this with nock, like so:
import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'
axios.defaults.adapter = httpAdapter
describe('foo', () => {
it('bar', () => {
nock('https://example.com:443')
.get('/example')
.reply(200, 'some payload')
// test...
})
})
score:38
I could do that following the steps:
- Create a folder __mocks__/ (as pointed by @Januartha comment)
- Implement an
axios.js
mock file - Use my implemented module on test
The mock will happen automatically
Example of the mock module:
module.exports = {
get: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
}),
post: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
if (url === '/something2') {
return Promise.resolve({
data: 'data2'
});
}
}),
create: jest.fn(function () {
return this;
})
};
score:194
Without using any other libraries:
import * as axios from "axios";
// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");
// ...
test("good response", () => {
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
// ...
});
test("bad response", () => {
axios.get.mockImplementation(() => Promise.reject({ ... }));
// ...
});
It is possible to specify the response code:
axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));
It is possible to change the mock based on the parameters:
axios.get.mockImplementation((url) => {
if (url === 'www.example.com') {
return Promise.resolve({ data: {...} });
} else {
//...
}
});
Jest v23 introduced some syntactic sugar for mocking Promises:
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
It can be simplified to
axios.get.mockResolvedValue({ data: {...} });
There is also an equivalent for rejected promises: mockRejectedValue
.
Further Reading:
- Jest mocking documentation
- A GitHub discussion that explains about the scope of the
jest.mock("axios")
line. - A related question which addresses applying the techniques above to Axios request interceptors.
Source: stackoverflow.com
Related Query
- How to implement Jest test for Axios and Hooks - useEffect
- how to re-render after getting axios response in jest test
- How to test axios api using jest and react testing library?
- how to jest test an async action with axios in react?
- How can I test custom callbacks passed to Axios API using jest + enzyme
- how to jest test an async action with axios in react ? - part 2
- How can I mock multiple get axios request in Jest unit test for an async action that calls a few more async actions?
- How to test an async function which does an axios request to an api using JEST in a React application
- How to test axios requests in jest
- How to test axios get request in useEffect using Jest and Enzyme?
- How do you test for the non-existence of an element using jest and react-testing-library?
- How do I test axios in Jest?
- How to test a className with the Jest and React testing library
- How do I test a jest console.log
- How to use Jest to test functions using crypto or window.msCrypto
- How to write test case for ErrorBoundary in React using Jest / Enzyme
- How to "mock" navigator.geolocation in a React Jest Test
- Jest + Enzyme: How to test an image src?
- How to unit test a react event handler that contains history.push using Jest and Enzyme?
- How to get test coverage from Jest while testing React.js App?
- How to unit test useEffect cleanUp return function using Jest and Enzyme
- How to exclude CSS module files from jest test suites?
- How do you test router match params with jest and enzyme?
- How to test useRef with Jest and react-testing-library?
- How to test for tooltip title in jest and testing/library
- How to test form submission in React with Jest and Enzyme? Cannot read property 'preventDefault' of undefined
- How to set a test for multiple fetches with Promise.all using jest
- React, Jest and Material-UI: How to test for content rendered in a modal or popover
- How to test snapshots with Jest and new React lazy 16.6 API
- How to test react-dropzone with Jest and react-testing-library?
More Query from same tag
- React-Reudx: Actions must be plain objects. Use custom middleware for async actions
- React state object turning into "[object Object]" on refresh using sessionStorage
- Where to make an Initial AJAX request from in ReactJS
- Javascript: Recursion returning undefined
- Why I can't apply redux's connect with material-ui withStyles?
- Type checking styled-components props in stateless component
- Prop not updating dynamically
- How do I trigger a route manually with React router?
- React child components positioning overlapping issue
- Redux Action not getting passed to reducer
- How to dynamically create a number of fields based on the number in another number input?
- React : Trigger function when the user stops typing
- How use react-redux connect with mapStateToProps,MapDispatchToProps and redux-router
- create-react-app unsupported node version
- Return boolean value from Material UI Radio to use in Yup .when Validation
- Hook Reflux store in React.createClass and trigger actions the right way
- Break out of ReactRouter when there is no match
- react useEffect how to update data if two different dependency arrays updates at the same time
- Remove specific product based on multiple factors
- How to set up nginx config for a React.js app deployed on AWS ECS with path-based routing load balancer
- how to pass functions through React components
- React: import local files from a dynamic location
- React-google-maps zoom issue
- Can not navigate to another screen with navigation.navigate
- How to change all value of items in a list in reactJS when onClick on an item
- material ui 'new' v5.0.0 injectFirst fails to set specificity
- Convert date using react-moment
- Redirect to page with different page layout in React
- React signup form
- React Redirect with data