Skip to content

Commit 34f61a6

Browse files
authored
Merge pull request #390 from garageScript/lessonsapi
closes #389 - Create api/lessons page that returns object of lessons data
2 parents 157d5f3 + f9d1aef commit 34f61a6

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

pages/api/lessons.test.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import lessonsAPI from './lessons'
2+
import noop from '../../helpers/noop'
3+
import * as getLessons from '../../graphql/queryResolvers/lessons'
4+
5+
describe('lessonsAPI', () => {
6+
const res = {
7+
json: jest.fn(noop),
8+
status: jest.fn(noop)
9+
}
10+
11+
getLessons.lessons = jest
12+
.fn()
13+
.mockReturnValue(['man', 'bear', 'pig', 'manbearpig'])
14+
15+
test('should respond with 200 status code when there is no error', async () => {
16+
await lessonsAPI(null, res)
17+
expect(res.status).toBeCalledWith(200)
18+
})
19+
20+
test('should respond with json data from lessons() when there is no error', async () => {
21+
await lessonsAPI(null, res)
22+
expect(res.json).toBeCalledWith(['man', 'bear', 'pig', 'manbearpig'])
23+
})
24+
25+
test('should respond with 500 status code when there is an error', async () => {
26+
getLessons.lessons = jest.fn().mockImplementation(() => {
27+
throw new Error('Error')
28+
})
29+
await lessonsAPI(null, res)
30+
expect(res.status).toBeCalledWith(500)
31+
})
32+
33+
test('should respond with error message when there is an error', async () => {
34+
getLessons.lessons = jest.fn().mockImplementation(() => {
35+
throw new Error('Error occured :(')
36+
})
37+
await lessonsAPI(null, res)
38+
expect(res.json).toBeCalledWith('Error occured :(')
39+
})
40+
})

pages/api/lessons.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { lessons } from '../../graphql/queryResolvers/lessons'
2+
import { LoggedRequest } from '../../@types/helpers'
3+
import { NextApiResponse } from 'next'
4+
5+
export default async (_: LoggedRequest, res: NextApiResponse) => {
6+
try {
7+
const allLessons = await lessons()
8+
res.status(200)
9+
res.json(allLessons)
10+
} catch (err) {
11+
res.status(500)
12+
res.json('Error occured :(')
13+
}
14+
}

0 commit comments

Comments
 (0)