Skip to content

Commit

Permalink
add test for the mongo connection + up to date .env samples based on …
Browse files Browse the repository at this point in the history
…Next 9.4.1 + MDX in jest
  • Loading branch information
eric-burel committed Jun 22, 2020
1 parent d814311 commit 2456a34
Show file tree
Hide file tree
Showing 18 changed files with 569 additions and 91 deletions.
3 changes: 3 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NEXT_PUBLIC_GRAPHQL_URI="http://localhost:3001"
MONGO_URI="mongodb+srv://johnDoe:[email protected]/sample_restaurants?retryWrites=true&w=majority"
APOLLO_SERVER_CORS_WHITELIST="http://localhost:3000"
3 changes: 0 additions & 3 deletions .env.development.sample

This file was deleted.

3 changes: 3 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NEXT_PUBLIC_GRAPHQL_URI="http://localhost:3001"
MONGO_URI="mongodb+srv://johnDoe:[email protected]/sample_restaurants?retryWrites=true&w=majority"
APOLLO_SERVER_CORS_WHITELIST="http://localhost:3000"
3 changes: 3 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NEXT_PUBLIC_GRAPHQL_URI="http://localhost:3001"
MONGO_URI="mongodb+srv://johnDoe:[email protected]/sample_restaurants?retryWrites=true&w=majority"
APOLLO_SERVER_CORS_WHITELIST="http://localhost:3000"
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

# misc
.DS_Store
.env*
.env*.local

# debug
npm-debug.log*
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@

[Read the docs](./docs)

## Install and run

```
yarn
cp .env.development.sample .env.development
cp .env.development.sample .env.production
yarn run dev
```

## Connect to a Vulcan backend

[If you don't know the awesome GraphQL framework Vulcan, get started here](http://vulcanjs.org/)
Expand Down
12 changes: 10 additions & 2 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ We have a unit tests for some key features and scripts of VNS, through the `test

This folder is ignored when running `yarn run test:unit`, to avoid bloating your own tests.

### MDX parsing, magic imports with ~

[jest-transformer-mdx](https://github.com/bitttttten/jest-transformer-mdx) allow importing .mdx also in Jest

## Unified testing patterns

We strive to unify testing patterns between Cypress and Jest where it makes sense.
Expand Down Expand Up @@ -271,6 +275,10 @@ Error tracking with Sentry?
Demo after and before hooks
Automatically enable debug in Cypress

### Jest

Load dotenv config in Jest

### GraphQL

Graphql code generator
Expand All @@ -290,10 +298,10 @@ Demo a Mongodb connection with Mongoose (maybe we could find a demo database onl

 ### Others


Remove debug routes from bundle
Pure JS support (no TS), in cypress, in code, in storybook, in jest...
PErformance testing?

Performance testing?
A way to debug which files are built in TypeScript
Default styling for MDX, using Material UI
Easy opt out of MDX
Expand Down
2 changes: 2 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ module.exports = {
transform: {
//"^.+\\.[jt]sx?$": "ts-jest",
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
// MDX support
"^.+\\.(md|mdx)$": "jest-transformer-mdx",
},

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
Expand Down
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"start": "next start",
"test": "npm run test:unit && npm run test:e2e",
"clean": "rm -Rf ./dist # clean various build folders",
"postinstall": "cp -n .env.development.sample .env.development # initialize dev config after first install",
"postinstall": "",
"build:static": "next build && next export",
"start:static": "serve ./out",
"start:test": "cross-env NODE_ENV=test npm run start # Start app in test mode",
Expand Down Expand Up @@ -67,7 +67,7 @@
"isomorphic-unfetch": "3.0.0",
"lodash": "^4.17.15",
"mongoose": "^5.9.19",
"next": "9.4.0",
"next": "^9.4.4",
"next-i18next": "5.0.0-beta.2",
"next-with-apollo": "5.0.1",
"react": "16.13.0",
Expand Down Expand Up @@ -97,6 +97,7 @@
"@types/shelljs": "^0.8.8",
"@typescript-eslint/eslint-plugin": "^2.21.0",
"@typescript-eslint/parser": "^2.21.0",
"add": "^2.0.6",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.1.0",
"cypress": "4.8.0",
Expand All @@ -105,12 +106,14 @@
"eslint-plugin-react-hooks": "^2.5.0",
"graphql-voyager": "^1.0.0-rc.31",
"jest": "^26.0.1",
"jest-transformer-mdx": "2.2.0",
"nyc": "^15.1.0",
"shelljs": "^0.8.4",
"source-map-support": "^0.5.19",
"start-server-and-test": "^1.11.0",
"ts-loader": "^7.0.5",
"ts-node": "^8.10.2",
"typescript": "^3.9.0"
"typescript": "^3.9.0",
"yarn": "^1.22.4"
}
}
17 changes: 10 additions & 7 deletions src/api/middlewares/mongoConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,43 @@ import mongoose from "mongoose";
// Import mongoose models here
import "~/api/mongoose/models";

/*
async function closeDbConnection() {
export async function closeDbConnection() {
try {
await mongoose.connection.close();
} catch (err) {
// Catch locally error
console.error(err);
}
}
*/

import debug from "debug";
const debugMongo = debug("vns:mongo");

// trigger the initial connection on app startup
export const connectToDb = async () => {
export const connectToDb = async (mongoUri: string) => {
if (![1, 2].includes(mongoose.connection.readyState)) {
debugMongo("Call mongoose connect");
return await mongoose.connect(process.env.MONGO_URI, {
return await mongoose.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}
debugMongo("Ran connectToDb, already connected or connecting to Mongo");
return false;
};

const mongoConnectionMiddleware = () => {
const mongoUri = process.env.MONGO_URI;
if (!mongoUri) throw new Error("MONGO_URI env variable is not defined");
// init the first database connection on server startup
connectToDb();
connectToDb(mongoUri);
// mongoose.set("useFindAndModify", false);

// then return a middleware that checks the connection on every call
return async (req: Request, res: Response, next) => {
try {
// To debug the number of connections in Mongo client: db.serverStatus().connections
await connectToDb();
await connectToDb(mongoUri);

// Do not forget to close connection on finish and close events
// NOTE: actually we don't need this. Db connection close should happen on lambda destruction instead.
Expand Down
1 change: 1 addition & 0 deletions src/components/home/home.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "~/types/mdx.d.ts"; // TODO: load this automatically
import Readme from "../../../README.md";

export default () => (
<div>
<em>
Expand Down
4 changes: 2 additions & 2 deletions src/components/home/tests/home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Home from "../home";

describe("components/home", () => {
test("renders home with React Testing", () => {
const { getByRole } = render(<Home />);
expect(getByRole("heading")).toHaveTextContent("Vulcan Next Starter");
const { queryByText } = render(<Home />);
expect(queryByText("Vulcan Next Starter")).not.toBeNull();
});
});
2 changes: 0 additions & 2 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import { getDataFromTree } from "@apollo/react-ssr";
// import environment from '@vulcan/multi-env-demo';
// console.log('imported environment', environment); // should display "server"/"client" depending on the environment, just a test

// import "@vulcan/react-i18n"; // enable i18n

function VNSApp({ Component, pageProps }: AppProps) {
useMuiApp(); // comment to disable Material UI
return (
Expand Down
4 changes: 2 additions & 2 deletions src/pages/api/debug/graphql-voyager.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// @see https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client-auth
import express from "express";
import cors from "cors";
import corsOptions from "~/lib/api/cors";
import getConfig from "next/config";
import corsOptions from "~/api/cors";
//import getConfig from "next/config";
import { express as voyagerMiddleware } from "graphql-voyager/middleware";

export const config = {
Expand Down
9 changes: 3 additions & 6 deletions src/pages/api/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ const resolvers = {
// Expected the database to be setup with the demo "restaurant" API from mongoose
async restaurants() {
const db = mongoose.connection;
const restaurants = await db
.collection("restaurants")
.find(null, null)
.limit(5)
.toArray();
return restaurants;
const restaurants = await db.collection("restaurants");
const results = await restaurants.find(null, null).limit(5).toArray();
return results;
},
},
};
Expand Down
6 changes: 4 additions & 2 deletions tests/vns/coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import path from "path";
import fs from "fs";
import shell from "shelljs";
import { spawn } from "child_process";
import debug from "debug";
const debugCoverage = debug("vns:coverage");

const basicSpec = "cypress/integration/vns/basic.spec.ts";

Expand Down Expand Up @@ -36,10 +38,10 @@ describe("code coverage", () => {
detached: true,
});
child.stdout.on("data", (data) => {
if (isDebug) console.log("STDOUT:", data.toString());
debugCoverage("STDOUT:", data.toString());
});
child.stderr.on("data", (data) => {
if (isDebug) console.log("STDERR:", data.toString());
debugCoverage("STDERR:", data.toString());
});
child.on("exit", (code) => {
try {
Expand Down
25 changes: 25 additions & 0 deletions tests/vns/mongoConnection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {
connectToDb,
closeDbConnection,
} from "../../src/api/middlewares/mongoConnection";
// TODO: setup dotenv like in Next
// @see https://github.com/VulcanJS/vulcan-next-starter/issues/47
if (!process.env.MONGO_URI) {
process.env.MONGO_URI =
"mongodb+srv://johnDoe:[email protected]/sample_restaurants?retryWrites=true&w=majority";
}

describe("api/middlewares/mongoConnection", () => {
afterEach(() => {
closeDbConnection();
});
it("connects to mongo db", async () => {
const res = await connectToDb(process.env.MONGO_URI); // you can define a .env.test to configure this
expect(res).toBeTruthy();
});
it("connects only one if already connecting", async () => {
await connectToDb(process.env.MONGO_URI); // you can define a .env.test to configure this
const newConnection = await connectToDb(process.env.MONGO_URI); // you can define a .env.test to configure this
expect(newConnection).toBe(false);
});
});
Loading

0 comments on commit 2456a34

Please sign in to comment.