Skip to content

remcohaszing/axios-test-instance

Repository files navigation

Axios Test Instance

Test NodeJS backends using Axios

build status codecov npm prettier jest

Table of Contents

Installation

npm install axios-test-instance

Usage

  1. 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 a beforeAll or beforeEach block.
  2. 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:

See also

License

MIT © Remco Haszing