Last active
May 9, 2020 16:06
-
-
Save romanlv/c12c2541212110968bc92ba19b176d1c to your computer and use it in GitHub Desktop.
Async support wrapper for node-mocks-http, allows to write unit tests for next.js api pages
This file contains hidden or 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 { createMocksAsync } from '../../../utils/node-mocks-http'; | |
// nextjs handler | |
import logout from '../../../pages/api/auth/logout'; | |
describe('logout api', () => { | |
it('should clear cookies and redirect to home', async () => { | |
const refreshToken = 'refresh_token_1'; | |
const { req, res, result } = createMocksAsync({ | |
method: 'GET', | |
url: '/api/auth/logout', | |
cookies: { | |
token: 'token_1', | |
}, | |
}); | |
// @ts-ignore | |
logout(req, res); | |
await result; | |
// expect something | |
}); | |
}); |
This file contains hidden or 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
/* eslint-disable no-underscore-dangle */ | |
import { Request, Response } from 'express'; | |
import httpMocks, { | |
MockRequest, | |
MockResponse, | |
RequestOptions, | |
ResponseOptions, | |
} from 'node-mocks-http'; | |
// const httpMocks = require('node-mocks-http'); | |
export interface Mocks<T1 extends Request, T2 extends Response> { | |
req: MockRequest<T1>; | |
res: MockResponse<T2>; | |
result: Promise<Array<any>>; | |
err: any; | |
} | |
// eslint-disable-next-line global-require | |
httpMocks.createResponse({ eventEmitter: require('events').EventEmitter }); | |
// this wrapper allows to wait for async handlers which is not supported by default | |
export function createMocksAsync<T1 extends Request = Request, T2 extends Response = Response>( | |
reqParams?: RequestOptions, | |
resParams?: ResponseOptions | |
): Mocks<T1, T2> { | |
let errResolver; | |
const error = new Promise((res) => { | |
errResolver = res; | |
}); | |
const { req, res } = httpMocks.createMocks<T1, T2>(reqParams, resParams); | |
let dataResolver: (data: object) => void | null; | |
const data = new Promise((resolve) => { | |
dataResolver = resolve; | |
}); | |
res.on('end', () => dataResolver(res._getData())); | |
const result = Promise.race([Promise.all([error, null]), Promise.all([null, data])]); | |
return { req, res, err: errResolver, result }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment