This package has been deprecated

Author message:

use axios-koa-router instead

axios-mock-request
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

Usage

import axios from 'axios';

const net = axios.create({ });

if(import.meta.env.VITE_AXIOS_MOCK) {
	// Use asynchronous import() to reduce the entry size of the production
	net.defaults.adapter = await (await import('axios-mock-request')).default({
		// where to load your mock-routes
		router: import('/@/mocks/index.ts'),
		// callback for debugs
		beforeResponse(ctx) { console.log(ctx) }
	})
}


net.get('/test/8754/666').then(res => console.log(res))
net.get('/test/my.car').then(res => console.log(res))
net.get('/test/2024-2030').then(res => console.log(res))
net.get('/test/foo-bar').then(res => console.log(res))
net.get('/test/bbccdd/ok?a=1').then(res => console.log(res))
net.get('/test/a/b/c/d/e').then(res => console.log(res))
net.get('/test/john?a=1&a=2&b[]=1&c[]=3&c[]=4&c[k]=5').then(res => console.log(res))

mocks/index.ts

import Router from 'axios-mock-request/router'

const router = new Router()

await router.use(/^\/TEST\/\d+$/i, import('./test'))

await router.use((ctx, next) => {
	// authorization checks
	if (ctx.req.headers.get('token') === 'wrong') {
		ctx.status = 401
		ctx.body = { error: 'auth failed' }
	} else {
		next()
	}
})

router.put(/^\/test\/\d+$/, (ctx) => {
	// request real internet
	// ctx.config.url = '/'
	// ctx.config.data = '{}'
	ctx.bypass = true
})

router.get('/test/:from(\\d+)-:to', (ctx) => {
	ctx.body = '/test/:from(\\d+)-:to <== ' + ctx.req.path
})

router.get('/test/:name', (ctx) => {
	ctx.body = '/test/:name <== ' + ctx.req.path
})

router.get('/test/(aa)?(bb)+cc*/:name', (ctx) => {
	ctx.body = '/test/(aa)?(bb)+cc*/:name <== ' + ctx.req.path
})

router.any('/test/**', (ctx) => {
	ctx.body = '/test/** <== ' + ctx.req.path
})

export default router

mocks/test/index.ts

import Router from 'axios-mock-request/router'

const router = new Router()

router.get('/:id', (ctx) => {
	ctx.body = ctx.req.regGroup
})

export default router

Router Path Syntax

https://expressjs.com/en/guide/routing.html

Readme

Keywords

none

Package Sidebar

Install

npm i axios-mock-request

Weekly Downloads

2

Version

1.1.2

License

MIT

Unpacked Size

15.3 kB

Total Files

17

Last publish

Collaborators

  • logaxn