Skip to content

Instantly share code, notes, and snippets.

@BrunoQuaresma
Last active July 18, 2023 17:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoQuaresma/d4956a27f29d88dc728cc826d2d9ed39 to your computer and use it in GitHub Desktop.
Save BrunoQuaresma/d4956a27f29d88dc728cc826d2d9ed39 to your computer and use it in GitHub Desktop.
NextApiResponse and NextApiRequest mocks
import { IncomingMessage } from 'http'
import {
NextApiRequestCookies,
NextApiRequestQuery,
} from 'next/dist/next-server/server/api-utils'
import { Socket } from 'net'
import { ServerResponse } from 'http'
import { NextApiRequest, NextApiResponse } from 'next'
import { Env } from 'next/dist/lib/load-env-config'
export type NextApiRequestOptions = Partial<NextApiRequestMock>
export class NextApiRequestMock extends IncomingMessage
implements NextApiRequest {
public query: NextApiRequestQuery = {}
public cookies: NextApiRequestCookies = {}
public env: Env = {}
public body: any
constructor(options?: NextApiRequestOptions) {
super(new Socket())
if (options) {
this.method = options.method
this.body = options.body
this.query = options.query || {}
this.headers = options.headers || {}
this.env = options.env || {}
}
}
}
export class NextApiResponseMock extends ServerResponse
implements NextApiResponse {
public body: any
public jsonBody: any
send(body: any) {
this.body = body
}
json(jsonBody: any) {
this.jsonBody = jsonBody
}
status(statusCode: number) {
this.statusCode = statusCode
return this
}
setPreviewData(
data: object | string,
options?: {
maxAge?: number
}
) {
return this
}
clearPreviewData() {
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment