Test NodeJS backends using Axios
npm install axios-test-instance
setTestApp
in a beforeAll
or beforeEach
block.request
and use it in tests.import { request, setTestApp } from 'axios-test-instance'
import { app } from './app.js'
beforeAll(async () => {
await setTestApp(app)
})
The method above works with Jest, but it might not work with your testing framework. For this use
case, a test instance can be created manually using createInstance
.
import { createInstance } from 'axios-test-instance'
import { app } from './app.js'
let instance
beforeAll(async () => {
instance = await createInstance(app)
})
afterAll(async () => {
await instance.close()
})
Chances are you’re already using an Axios instance in your frontend. In this case, patchInstance
can be used to patch this instance instead.
import { patchInstance } from 'axios-test-instance'
import { app } from './app.js'
import { request } from './request.js'
let instance
beforeAll(async () => {
instance = await patchInstance(request, app)
})
afterAll(async () => {
await instance.close()
})
Now requests made using this instance, will be redirected to the app under test.
For usages examples, have a look at our test cases: