A Lightweight library for testing Next.js API routes
MIT License
npm install --save-dev next-test-api-routes
import {createMocks, parseResponse} from 'next-test-api-routes'
const route = require('./api/hello')
describe('api/hello', () => {
it('should return a 200 status code', async () => {
const {req, res} = createMocks({
method: 'GET',
})
const resp = parseResponse(await route(req, res))
expect(res.statusCode).toBe(200)
})
it('should return a JSON object', async () => {
const {req, res} = createMocks({
method: 'POST',
body: {
name: 'John Doe',
},
})
const resp = parseResponse(await route(req, res))
expect(resp.json().message).toBe('Hello John Doe')
})
})
Creates a mock request and response object.
options
Object
options.method
string (optional, default 'GET'
)options.body
Object (optional, default undefined
)options.query
Object (optional, default {}
)options.headers
Object (optional, default {}
)options.cookies
Object (optional, default {}
)options.url
string (optional, default /
)options.params
Object (optional, default {}
)const {req, res} = createMocks({
method: 'GET',
body: {
name: 'John Doe',
},
query: {
page: 1,
}
})
Parses the response object from the route handler.
response
Object
response
Object
response.json
Function Returns the parsed JSON object.response.body
string The response body as a string.response.headers
Object The response headers.response.statusCode
number The response status code.const {req, res} = createMocks({
method: 'GET',
})
const resp = parseResponse(await route(req, res))
expect(resp.json().message).toBe('Hello World')
This project is licensed under the MIT License - see the LICENSE file for details