axios-test-instance
v8.0.0
Published
Test NodeJS backends using Axios
Downloads
8,455
Maintainers
Readme
Axios Test Instance
Test NodeJS backends using Axios
Installation
npm install axios-test-instance
Usage
- Create an Axios test instance by passing your app, which may be a Koa app, an Express app, or an
HTTP request handler, to
setTestApp
in abeforeAll
orbeforeEach
block. - Import
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.
Examples
For usages examples, have a look at our test cases:
- Koa example
- Express example
- Fastify example (See #2 for limitations)
- HTTP callback example
- End to end example
See also
- jest-axios-snapshot asserts axios responses using jest snapshots.