How to Mock Axios With Vitest?


Unit testing involving requests can be challenging. It’s crucial to mock requests because we can’t depend on external resources for the consistency of testing. Please keep in mind that, when testing requests, it’s not enough to only test the successful cases; we also need to test failed cases to cover all possible outcomes.

Skipping the lengthy explanation, let’s jump straight into the code example below.

Code Example

This is a straightforward function named sayHello(). It contains an Axios request to fetch the name “John”. That’s its sole purpose.

// hello.js

export const sayHello = async () => {
    const response = await axios.get('http://some-url')
    const { name } = response
    return `Hello, ${name}`
}
JavaScript

In the hello.js test file, the testing process covers both successful and failed requests. Since the request depends on an external service, mocking is necessary for testing.

// hello.test.js

import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest'
import axios from 'axios'
import { sayHello } from './hello'

describe('SayHelloTest', () => {
    afterEach(async () => {
        // Restore all mocks after each test
        vi.restoreAllMocks()
    })

    test('Should handle Axios rejected promise', async () => {
        // Mock Axios request using vitest
        vi.spyOn(axios, 'get').mockRejectedValue(new Error('Failed to fetch'))
        await expect(sayHello()).rejects.toThrow('Failed to fetch')
    })

    test('Should handle Axios resolved promise', async () => {
        // Mock Axios request using vitest
        vi.spyOn(axios, 'get').mockResolvedValue({ name: 'John' })
        await expect(sayHello()).resolves.toBe('Hello, John')
    })
})
JavaScript

Explanation

vi.spyOn(axios, 'get').mockRejectedValue(new Error('Failed to fetch'))

This line is using the vi.spyOn function provided by Vitest to mock the axios.get function. It means that whenever axios.get is called in the code being tested, it will reject the promise with an error message “Failed to fetch”.

await expect(sayHello()).rejects.toThrow('Failed to fetch')

This line is testing the function sayHello() to see if it properly handles a rejected Axios promise. It uses expect to assert that calling sayHello() should result in a rejected promise with the error message “Failed to fetch”.

vi.spyOn(axios, 'get').mockResolvedValue({ name: 'John' })

Similar to the previous test case, this line mocks the axios.get function, but this time it resolves the promise with an object { name: 'John' }.

await expect(sayHello()).resolves.toBe('Hello, John')

This line tests the function sayHello() to see if it properly handles a resolved Axios promise. It expects that calling sayHello() will result in a resolved promise with the value 'Hello, John'.

Overall, these tests ensure that the sayHello() function behaves correctly when making Axios requests, handling both resolved and rejected promises appropriately.

Leave a Reply

Your email address will not be published. Required fields are marked *