⚡️ Next Test API Routes
Installation
npm install --save-dev next-test-api-routes
Usage
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')
})
})
Methods
createMocks
Creates a mock request and response object.
Parameters
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 {}
)
Examples
const {req, res} = createMocks({
method: 'GET',
body: {
name: 'John Doe',
},
query: {
page: 1,
}
})
parseResponse
Parses the response object from the route handler.
Parameters
Returns
response
Objectresponse.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.
Examples
const {req, res} = createMocks({
method: 'GET',
})
const resp = parseResponse(await route(req, res))
expect(resp.json().message).toBe('Hello World')
License
This project is licensed under the MIT License - see the LICENSE file for details