Skip to content

Commit 2174570

Browse files
committed
Add test service, rename methods
1 parent 53fdd2f commit 2174570

File tree

7 files changed

+65
-48
lines changed

7 files changed

+65
-48
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "api-next",
3-
"version": "1.0.0",
3+
"version": "1.1.0",
44
"repository": "https://github.com/imflavio/api-next",
55
"author": "Flávio Carvalho <[email protected]>",
66
"license": "MIT",
@@ -24,6 +24,7 @@
2424
"dependencies": {
2525
"express-validator": "6.6.1",
2626
"morgan": "1.10.0",
27+
"node-mocks-http": "1.8.1",
2728
"simple-http-status": "1.1.0"
2829
},
2930
"devDependencies": {
@@ -35,7 +36,6 @@
3536
"husky": "4.2.5",
3637
"prettier": "2.0.5",
3738
"eslint-plugin-prettier": "3.1.4",
38-
"node-mocks-http": "1.8.1",
3939
"tsdx": "0.13.2",
4040
"tslib": "2.0.1",
4141
"typescript": "4.0.2",

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import * as hook from './hooks'
22
export { hook }
33

4-
export * from 'services.ts'
4+
export { createService } from './services'
5+
export { testService } from './testing'
56
export * from './mongoose'
67
export * from './types'
78
export { BadRequestError } from './errors/bad-request-error'

src/mongoose.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as mongoose from 'mongoose'
33
import { ServiceMethods } from './types'
44
import { NotFoundError } from './errors/not-found-error'
55

6-
export const createMongooseService = (
6+
export const createMongooseMethods = (
77
Model: ReturnType<typeof mongoose.model>,
88
): ServiceMethods => ({
99
find: async () => Model.find(),

src/testing.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { createMocks, RequestOptions, ResponseOptions } from 'node-mocks-http'
2+
import { NextApiRequest, NextApiResponse } from 'next'
3+
4+
import { createService } from './services'
5+
6+
interface ServiceResponse<T = any> {
7+
statusCode: number
8+
data: T
9+
req: NextApiRequest
10+
res: NextApiResponse
11+
}
12+
13+
export const testService = async <Response>(
14+
service: ReturnType<typeof createService>,
15+
reqOptions: RequestOptions,
16+
resOptions?: ResponseOptions,
17+
): Promise<ServiceResponse<Response>> => {
18+
const { req, res } = createMocks(reqOptions, resOptions)
19+
await service(req, res)
20+
21+
return {
22+
statusCode: res._getStatusCode(),
23+
data: JSON.parse(res._getData()),
24+
req,
25+
res,
26+
}
27+
}

test/api.test.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import { createMocks } from 'node-mocks-http'
21
import { Status, Method } from 'simple-http-status'
32

4-
import { createService } from '../src'
3+
import { createService, testService } from '../src'
54

65
const tests = [
76
{},
@@ -64,20 +63,20 @@ tests.map((services) => {
6463
const isAvailable = availableServices.includes(service.name)
6564

6665
return test(`is "${service.name}" available? ${isAvailable}`, async () => {
67-
const { req, res } = createMocks(service.reqOptions)
68-
await handler(req, res)
69-
70-
const statusCode = res._getStatusCode()
66+
const { statusCode, data } = await testService(
67+
handler,
68+
service.reqOptions,
69+
)
7170

7271
if (isAvailable) {
7372
expect(statusCode).not.toBe(Status.HTTP_404_NOT_FOUND)
74-
expect(JSON.parse(res._getData())).toEqual(
73+
expect(data).toEqual(
7574
// @ts-ignore
7675
await services[service.name](),
7776
)
7877
} else {
7978
expect(statusCode).toBe(Status.HTTP_404_NOT_FOUND)
80-
expect(JSON.parse(res._getData())).toEqual({
79+
expect(data).toEqual({
8180
errors: [{ message: 'Not Found' }],
8281
})
8382
}

test/find.test.ts

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
1-
import { createMocks } from 'node-mocks-http'
21
import { Status } from 'simple-http-status'
32

4-
import { createService, ApiNextQuery } from '../src'
3+
import { createService, ApiNextQuery, testService } from '../src'
54

65
describe('[createService/find]', () => {
76
test('Should be able to return all results', async () => {
8-
const handler = createService({
7+
const service = createService({
98
find: async () => ['one', 'two'],
109
})
11-
const { req, res } = createMocks({
10+
const { statusCode, data } = await testService(service, {
1211
method: 'GET',
1312
})
14-
await handler(req, res)
15-
16-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
17-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
13+
expect(statusCode).toBe(Status.HTTP_200_OK)
14+
expect(data).toMatchInlineSnapshot(`
1815
Array [
1916
"one",
2017
"two",
@@ -26,21 +23,19 @@ describe('[createService/find]', () => {
2623
interface MyQuery extends ApiNextQuery {
2724
filter: string
2825
}
29-
const handler = createService({
26+
const service = createService({
3027
find: async (query: MyQuery) =>
3128
['one', 'two'].filter((item) => item.includes(query.filter)),
3229
})
33-
const { req, res } = createMocks({
30+
const { statusCode, data } = await testService(service, {
3431
method: 'GET',
3532
query: {
3633
filter: 'one',
3734
},
3835
})
3936

40-
await handler(req, res)
41-
42-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
43-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
37+
expect(statusCode).toBe(Status.HTTP_200_OK)
38+
expect(data).toMatchInlineSnapshot(`
4439
Array [
4540
"one",
4641
]

test/get.test.ts

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,75 @@
1-
import { createMocks } from 'node-mocks-http'
21
import { Status } from 'simple-http-status'
32

4-
import { createService } from '../src'
3+
import { createService, testService } from '../src'
54

65
describe('[createService/get]', () => {
76
test('Should be able to use default id in query', async () => {
8-
const handler = createService({
7+
const service = createService({
98
get: async (pk) => ({
109
message: `Your favorite animal is ${pk}`,
1110
}),
1211
})
13-
const { req, res } = createMocks({
12+
const { statusCode, data } = await testService(service, {
1413
method: 'GET',
1514
query: {
1615
id: 'cat',
1716
},
1817
})
19-
await handler(req, res)
2018

21-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
22-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
19+
expect(statusCode).toBe(Status.HTTP_200_OK)
20+
expect(data).toMatchInlineSnapshot(`
2321
Object {
2422
"message": "Your favorite animal is cat",
2523
}
2624
`)
2725
})
2826
test('Should be able to use default pk in query', async () => {
29-
const handler = createService({
27+
const service = createService({
3028
get: async (pk) => ({
3129
message: `Your favorite animal is ${pk}`,
3230
}),
3331
})
34-
const { req, res } = createMocks({
32+
const { statusCode, data } = await testService(service, {
3533
method: 'GET',
3634
query: {
3735
pk: 'fish',
3836
},
3937
})
40-
await handler(req, res)
4138

42-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
43-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
39+
expect(statusCode).toBe(Status.HTTP_200_OK)
40+
expect(data).toMatchInlineSnapshot(`
4441
Object {
4542
"message": "Your favorite animal is fish",
4643
}
4744
`)
4845
})
4946

5047
test('Should be able to use custom pk in query', async () => {
51-
const handler = createService({
48+
const service = createService({
5249
pk: {
5350
name: 'animal',
5451
},
5552
get: async (pk) => ({
5653
message: `Your favorite animal is ${pk}`,
5754
}),
5855
})
59-
const { req, res } = createMocks({
56+
const { statusCode, data } = await testService(service, {
6057
method: 'GET',
6158
query: {
6259
animal: 'dog',
6360
},
6461
})
65-
await handler(req, res)
6662

67-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
68-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
63+
expect(statusCode).toBe(Status.HTTP_200_OK)
64+
expect(data).toMatchInlineSnapshot(`
6965
Object {
7066
"message": "Your favorite animal is dog",
7167
}
7268
`)
7369
})
7470

7571
test('Should be able to use custom pk in query and cast it', async () => {
76-
const handler = createService({
72+
const service = createService({
7773
pk: {
7874
name: 'animal',
7975
cast: (pk) => `__${pk}__`,
@@ -82,16 +78,15 @@ describe('[createService/get]', () => {
8278
message: `Your favorite animal is ${pk}`,
8379
}),
8480
})
85-
const { req, res } = createMocks({
81+
const { statusCode, data } = await testService(service, {
8682
method: 'GET',
8783
query: {
8884
animal: 'dog',
8985
},
9086
})
91-
await handler(req, res)
9287

93-
expect(res._getStatusCode()).toBe(Status.HTTP_200_OK)
94-
expect(JSON.parse(res._getData())).toMatchInlineSnapshot(`
88+
expect(statusCode).toBe(Status.HTTP_200_OK)
89+
expect(data).toMatchInlineSnapshot(`
9590
Object {
9691
"message": "Your favorite animal is __dog__",
9792
}

0 commit comments

Comments
 (0)