Skip to content

Commit

Permalink
feat(Next): Change unit test approach to HTTP fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
danactive committed May 2, 2021
1 parent a304aa2 commit 3400e08
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 106 deletions.
120 changes: 34 additions & 86 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
"eslint-plugin-react-hooks": "^1.7.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^25.1.0",
"next-test-api-route-handler": "^1.2.24",
"node-fetch": "^2.6.1",
"node-mocks-http": "^1.10.1",
"react-test-renderer": "^16.12.0"
},
"license": "MIT"
Expand Down
37 changes: 18 additions & 19 deletions app/pages/api/galleries/__tests__/index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
/* eslint-disable no-underscore-dangle */
import { createMocks } from 'node-mocks-http'
import { testApiHandler } from 'next-test-api-route-handler'

import handleEndpoints from '..'
import handler from '..'

describe('Galleries API', () => {
describe('Expect result', () => {
test('* GET has galleries', async () => {
const { req, res } = createMocks({
method: 'GET',
})
const test = async ({ fetch }) => {
const response = await fetch({ method: 'GET' })
const result = await response.json()

await handleEndpoints(req, res)
expect(res._getStatusCode()).toBe(200)
expect(response.status).toBe(200)

const result = JSON.parse(res._getData())
expect(result.galleries.length).toBeGreaterThan(0)
expect(result.galleries.includes('demo')).toBeTruthy()
expect(result.galleries.length).toBeGreaterThan(0)
expect(result.galleries.includes('demo')).toBeTruthy()
}
await testApiHandler({ handler, test })
})
})

describe('Expect error', () => {
test('* POST verb is denied', async () => {
const { req, res } = createMocks({
method: 'POST',
})
const test = async ({ fetch }) => {
const response = await fetch({ method: 'POST' })
const result = await response.json()

await handleEndpoints(req, res)
expect(res._getStatusCode()).toBe(405)
expect(response.status).toBe(405)

const result = JSON.parse(res._getData())
expect(result.galleries.length).toBe(0)
expect(result.galleries.includes('demo')).toBeFalsy()
expect(result.galleries.length).toBe(0)
expect(result.galleries.includes('demo')).toBeFalsy()
}
await testApiHandler({ handler, test })
})
})
})

0 comments on commit 3400e08

Please sign in to comment.