axios-test-instance

Test NodeJS backends using Axios

MIT License

Downloads
4K
Stars
10
Committers
1

Axios Test Instance

Test NodeJS backends using Axios

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