Simplifying the struggle of mocking and reimplementing NextAPIRequests and NextAPIResponses in order to test and validate NextJS serverless functions.
Choose your favorite package manager to install the next-testing library
npm install --save-dev @next-testing/api
yarn add -D @next-testing/api
pnpm add -D @next-testing/api
import ServerlessFunctionApi from './pages/api/v1/myApi'
import { NextApiRequestBuilder, ResponseMock } from '@next-testing/api'
test("Get Request and Response Mock", () => {
const req = new NextApiRequestBuilder().setMethod('GET').build()
const res = ResponseMock<MyResult>()
ServerlessFunctionApi(req, res)
expect(res.getStatusCode()).toEqual(405)
expect(res.getBodyJson()).toStrictEqual({
success: false,
message: 'Method not allowed',
})
})
import ServerlessFunctionApi from './pages/api/v1/myApi'
import { NextApiRequestBuilder, ResponseMock } from '@next-testing/api'
it('Post Request and Response Mock', async () => {
const req = new NextApiRequestBuilder().setMethod('POST').build()
const res = ResponseMock<MyResult>()
ServerlessFunctionApi(req, res)
expect(res.getStatusCode()).toEqual(401)
expect(res.getBodyJson()).toStrictEqual({
success: false,
message: 'access denied',
})
})
import ServerlessFunctionApi from './pages/api/v1/myApi'
import { NextApiRequestBuilder, ResponseMock } from '@next-testing/api'
it('Mock Request and Response with headers', async () => {
const req = new NextApiRequestBuilder()
.setMethod('POST')
.setHeaders({ authorization: 'Bearer ABC123' })
.build()
const res = ResponseMock<CronResult>()
ServerlessFunctionApi(req, res)
expect(res.getStatusCode()).toEqual(401)
expect(res.getBodyJson()).toStrictEqual({
success: false,
message: 'access denied',
})
})
import ServerlessFunctionApi from './pages/api/v1/myApi'
import { NextApiRequestBuilder, ResponseMock } from '@next-testing/api'
it('Mock Request and Response with headers', async () => {
const req = new NextApiRequestBuilder()
.setMethod('POST')
.setHeaders({ authorization: 'Bearer ABC123' })
.setCookies({ apiKey: "mytoken" })
.setBody({
posts: [{
content: "hello world"
}]
})
.build()
const res = ResponseMock<CronResult>()
ServerlessFunctionApi(req, res)
expect(res.getStatusCode()).toEqual(401)
expect(res.getBodyJson()).toStrictEqual({
success: false,
message: 'access denied',
})
})
If your handler depends on some parameters found in the path, eg. it's defined
in pages/api/[foo]/echo
, then you can specify it with setQuery()
.
import EchoHandler from './pages/api/[foo]/echo'
import { NextApiRequestBuilder, ResponseMock } from '@next-testing/api'
it('Mock Request and Response with route parameters', async () => {
const req = new NextApiRequestBuilder()
.setMethod('GET')
.setQuery({
foo: 'hello'
})
.build()
const res = ResponseMock()
EchoHandler(req, res)
expect(res.getStatusCode()).toEqual(200)
expect(res.getBodyJson()).toStrictEqual({
foo: 'hello',
})
})