axios jest code example
Example 1: jest axios manual mock
const axios = require('axios')
module.exports = axios.get
const axios = require('axios')
module.exports = {
get: async () => {
const url = 'https://jsonplaceholder.typicode.com/posts'
const response = await axios.get(url)
return response.data
}
}
const axiosMock = require('../axios')
test('async axios action users with mock', async (done) => {
const url = 'https://jsonplaceholder.typicode.com/users'
response = await axiosMock(url)
expect(response).toBeDefined()
expect(response.length).toBe(100);
done()
});
Example 2: jest mock implementation
describe("mockImplementation", () => {
test("function", () => {
const mockFn1 = jest.fn().mockImplementation(() => 42);
const mockFn2 = jest.fn(() => 42);
expect(mockFn1()).toBe(42);
expect(mockFn2()).toBe(42);
});