Skip to content

Commit

Permalink
chore: add test helper
Browse files Browse the repository at this point in the history
  • Loading branch information
QingWei-Li committed Sep 5, 2021
1 parent b7b11fb commit 3fd5cc2
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 26 deletions.
26 changes: 0 additions & 26 deletions __tests__/api/tree.test.ts

This file was deleted.

1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ module.exports = {
moduleNameMapper: {
'pages/(.*)$': '<rootDir>/pages/$1',
'libs/(.*)$': '<rootDir>/libs/$1',
'tests/(.*)$': '<rootDir>/tests/$1',
},
}
20 changes: 20 additions & 0 deletions tests/api/tree.test.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 18 additions & 0 deletions tests/helper.ts
Original file line number Diff line number Diff line change
@@ -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>

0 comments on commit 3fd5cc2

Please sign in to comment.