Skip to content

Commit

Permalink
#17 Use @ljosberinn Lambda Test Util for API tests
Browse files Browse the repository at this point in the history
  • Loading branch information
blms committed Aug 3, 2020
1 parent 1b6d41b commit cf3c272
Show file tree
Hide file tree
Showing 10 changed files with 2,107 additions and 796 deletions.
2,524 changes: 1,773 additions & 751 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@testing-library/react-hooks": "^3.3.0",
"@types/mongodb": "^3.5.25",
"babel-jest": "^25.1.0",
"cookie": "^0.4.1",
"eslint-config-airbnb": "^18.2.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^23.17.1",
Expand All @@ -63,6 +64,6 @@
"jest": "^25.1.0",
"jest-fetch-mock": "^3.0.3",
"react-test-renderer": "^16.12.0",
"supertest": "^4.0.2"
"test-listen": "^1.1.0"
}
}
4 changes: 2 additions & 2 deletions src/__mocks__/next-auth/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { getObjectId } = require('mongo-seeding');

const jwt = jest.genMockFromModule('next-auth/jwt');

function getJwt() {
function getToken() {
return {
exp: 1000,
user: {
Expand All @@ -13,5 +13,5 @@ function getJwt() {
};
}

jwt.getJwt = getJwt;
jwt.getToken = getToken;
module.exports = jwt;
23 changes: 0 additions & 23 deletions src/__tests__/api/document.test.js

This file was deleted.

53 changes: 53 additions & 0 deletions src/__tests__/api/document.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import nc from 'next-connect';
import { testLambda } from '../../utils/lambdaTestUtil';
import postDocument from '../../utils/dbUtil';
import { expectJSONBodyMiddleware } from '../../middlewares/expectJSONBody';
import {
RequestInitMethod,
} from '../../utils/requestMethods';

afterEach(jest.clearAllMocks);

const url = '/api/document';
const middleware = expectJSONBodyMiddleware;
const docRoute = nc().post(postDocument);

test('should be a function', () => {
expect(docRoute).toBeInstanceOf(Function);
});

test('results in 404 on get', async () => {
const method: RequestInitMethod = 'get';
const response = await testLambda(docRoute, {
method,
middleware,
url,
});

expect(response.status).toBe(404);
});

test('results in 400 on empty post', async () => {
const method: RequestInitMethod = 'post';
const response = await testLambda(docRoute, {
method,
middleware,
url,
});

expect(response.status).toBe(400);
});

test('results in 400 on post with missing title', async () => {
const method: RequestInitMethod = 'post';
const response = await testLambda(docRoute, {
method,
middleware,
url,
body: {
'notes':'test',
},
});

expect(response.status).toBe(400);
});
29 changes: 29 additions & 0 deletions src/middlewares/expectJSONBody.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { NextApiResponse, NextApiRequest } from 'next';
import { Middleware } from 'next-connect';

/**
* Middleware accepting exclusively valid JSON as req.body, if existing
* This utility courtesy of Gerrit Alex (@ljosberinn)
* From @ljosberinn/personal-react-boilerplate on GitHub
* Released under MIT License, 2020
*/

export const expectJSONBodyMiddleware: Middleware<NextApiRequest, NextApiResponse> = (req, res, next) => {
if (req.body.length > 0) {
try {
const body = JSON.parse(req.body);

if (!(body instanceof Object)) {
return res.status(400).end();
}

req.body = body;
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
return res.status(400).end();
}
}

next();
};
4 changes: 0 additions & 4 deletions src/setupTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,3 @@
// learn more: https://github.com/testing-library/jest-dom

import '@testing-library/jest-dom/extend-expect';

import fetchMock from 'jest-fetch-mock';

fetchMock.enableMocks();
36 changes: 21 additions & 15 deletions src/utils/dbUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import jwt from 'next-auth/jwt';
const secret = process.env.AUTH_SECRET;

const postDocument = async (req, res) => {
const token = await jwt.getJwt({ req, secret });
const token = await jwt.getToken({ req, secret });
if (token && token.exp > 0) {
const dateCreated = new Date(Date.now());
const {
Expand Down Expand Up @@ -64,20 +64,26 @@ const postDocument = async (req, res) => {
delete metadata[key];
}
});
await req.db
.collection('documents')
.insert(
{
owner: ObjectID(token.user.id),
createdAt: dateCreated,
updatedAt: dateCreated,
...metadata,
},
(err, doc) => {
if (err) throw err;
res.status(200).json(doc);
},
);
if (Object.keys(metadata).length === 0) {
res.status(400).json({ error: '400 No request body' });
} else if (!metadata.title) {
res.status(400).json({ error: '400 Missing title' });
} else {
await req.db
.collection('documents')
.insert(
{
owner: ObjectID(token.user.id),
createdAt: dateCreated,
updatedAt: dateCreated,
...metadata,
},
(err, doc) => {
if (err) throw err;
res.status(200).json(doc);
},
);
}
} else res.status(403).json({ error: '403 Invalid or expired token' });
};
export default postDocument;
Loading

0 comments on commit cf3c272

Please sign in to comment.