chore: add test helper

This commit is contained in:
liqingwei 2021-09-05 19:28:50 +08:00
parent b7b11fb7f0
commit 3fd5cc25c3
4 changed files with 39 additions and 26 deletions

View File

@ -1,26 +0,0 @@
import { createServer, IncomingMessage, Server, ServerResponse } from 'http'
import { apiResolver } from 'next/dist/server/api-utils'
import treeHandler from 'pages/api/tree'
import supertest from 'supertest'
describe('/api/tree', () => {
let server: Server
beforeEach(async () => {
const requestHandler = (
request: IncomingMessage,
response: ServerResponse
) => apiResolver(request, response, undefined, treeHandler, {} as any, true)
server = createServer(requestHandler)
})
afterEach(() => {
server.close()
})
test('create note', async () => {
const result = await supertest(server).get('/api/tree').expect(200)
expect(result.body).toBeDefined()
})
})

View File

@ -16,5 +16,6 @@ module.exports = {
moduleNameMapper: {
'pages/(.*)$': '<rootDir>/pages/$1',
'libs/(.*)$': '<rootDir>/libs/$1',
'tests/(.*)$': '<rootDir>/tests/$1',
},
}

20
tests/api/tree.test.ts Normal file
View File

@ -0,0 +1,20 @@
import treeHandler from 'pages/api/tree'
import { mockServer } from 'tests/helper'
describe('/api/tree', () => {
let app: mockServer
beforeEach(async () => {
app = mockServer(treeHandler)
})
afterEach(() => {
app.server.close()
})
test('fetch tree', async () => {
const result = await app.request.get('/api/tree').expect(200)
expect(result.body).toBeDefined()
})
})

18
tests/helper.ts Normal file
View File

@ -0,0 +1,18 @@
import { createServer, IncomingMessage, ServerResponse } from 'http'
import { ApiRequest, ApiResponse } from 'libs/server/connect'
import { NextConnect } from 'next-connect'
import { apiResolver } from 'next/dist/server/api-utils'
import supertest from 'supertest'
export const mockServer = (handler: NextConnect<ApiRequest, ApiResponse>) => {
const requestHandler = (request: IncomingMessage, response: ServerResponse) =>
apiResolver(request, response, undefined, handler, {} as any, true)
const server = createServer(requestHandler)
return {
server,
request: supertest(server),
}
}
export type mockServer = ReturnType<typeof mockServer>