Last active
July 18, 2023 17:12
-
-
Save BrunoQuaresma/d4956a27f29d88dc728cc826d2d9ed39 to your computer and use it in GitHub Desktop.
NextApiResponse and NextApiRequest mocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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