From cd415e75d6df4ade18a04007a95e8fc8fd82dd97 Mon Sep 17 00:00:00 2001 From: Vlad Holubiev Date: Thu, 18 Apr 2019 14:18:43 +0300 Subject: [PATCH] Simplify mongodb example by using preset (#8318) * docs: simplify mongodb example by using preset I've just published a Jest preset to simplify usage. Since I was the author of the original tutorial, the code underneath remained the same * docs: update CHANGELOG.md * style: apply prettier style suggestions * docs: update v23 version doc * docs: leave original page metadata for v23 * docs: update v24 versioned doc page --- CHANGELOG.md | 1 + docs/MongoDB.md | 155 ++++-------------- .../versioned_docs/version-23.x/MongoDB.md | 153 ++++------------- .../versioned_docs/version-24.0/MongoDB.md | 155 ++++-------------- 4 files changed, 106 insertions(+), 358 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6699df1d4b9..874df7600df7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ ### Chore & Maintenance - `[expect]` Fix label and add opposite assertion for toEqual tests ([#8288](https://github.com/facebook/jest/pull/8288)) +- `[docs]` Mention Jest MongoDB Preset ([#8318](https://github.com/facebook/jest/pull/8318)) ### Performance diff --git a/docs/MongoDB.md b/docs/MongoDB.md index f12bdca10018..3610da622673 100644 --- a/docs/MongoDB.md +++ b/docs/MongoDB.md @@ -5,142 +5,57 @@ title: Using with MongoDB With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). -## A jest-mongodb example +## Use jest-mongodb Preset -The basic idea is to: +[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB. -1. Spin up in-memory mongodb server -2. Export a global variable with mongo URI -3. Write tests for queries / aggregations using a real database ✨ -4. Shut down mongodb server using Global Teardown +1. First install `@shelf/jest-mongodb` -Here's an example of the GlobalSetup script - -```js -// setup.js -const path = require('path'); - -const fs = require('fs'); - -const {MongoMemoryServer} = require('mongodb-memory-server'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -const mongod = new MongoMemoryServer({ - autoStart: false, -}); - -module.exports = async () => { - if (!mongod.isRunning) { - await mongod.start(); - } - - const mongoConfig = { - mongoDBName: 'jest', - mongoUri: await mongod.getConnectionString(), - }; - - // Write global config to disk because all tests run in different contexts. - fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig)); - - // Set reference to mongod in order to close the server during teardown. - global.__MONGOD__ = mongod; -}; +``` +yarn add @shelf/jest-mongodb --dev ``` -Then we need a custom Test Environment for Mongo - -```js -// mongo-environment.js -const NodeEnvironment = require('jest-environment-node'); - -const path = require('path'); - -const fs = require('fs'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -class MongoEnvironment extends NodeEnvironment { - constructor(config) { - super(config); - } - - async setup() { - console.log('Setup MongoDB Test Environment'); - - const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8')); - - this.global.__MONGO_URI__ = globalConfig.mongoUri; - this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName; - - await super.setup(); - } - - async teardown() { - console.log('Teardown MongoDB Test Environment'); - - await super.teardown(); - } +2. Specify preset in your Jest configuration: - runScript(script) { - return super.runScript(script); - } +```json +{ + "preset": "@shelf/jest-mongodb" } - -module.exports = MongoEnvironment; ``` -Finally we can shut down mongodb server +3. Write your test ```js -// teardown.js -module.exports = async function() { - await global.__MONGOD__.stop(); -}; -``` +const {MongoClient} = require('mongodb'); -With all the things set up, we can now write our tests like this: +describe('insert', () => { + let connection; + let db; -```js -// test.js -const {MongoClient} = require('mongodb'); + beforeAll(async () => { + connection = await MongoClient.connect(global.__MONGO_URI__, { + useNewUrlParser: true, + }); + db = await connection.db(global.__MONGO_DB_NAME__); + }); -let connection; -let db; + afterAll(async () => { + await connection.close(); + await db.close(); + }); -beforeAll(async () => { - connection = await MongoClient.connect(global.__MONGO_URI__); - db = await connection.db(global.__MONGO_DB_NAME__); -}); + it('should insert a doc into collection', async () => { + const users = db.collection('users'); -afterAll(async () => { - await connection.close(); - await db.close(); -}); + const mockUser = {_id: 'some-user-id', name: 'John'}; + await users.insertOne(mockUser); -it('should aggregate docs from collection', async () => { - const files = db.collection('files'); - - await files.insertMany([ - {type: 'Document'}, - {type: 'Video'}, - {type: 'Image'}, - {type: 'Document'}, - {type: 'Image'}, - {type: 'Document'}, - ]); - - const topFiles = await files - .aggregate([ - {$group: {_id: '$type', count: {$sum: 1}}}, - {$sort: {count: -1}}, - ]) - .toArray(); - - expect(topFiles).toEqual([ - {_id: 'Document', count: 3}, - {_id: 'Image', count: 2}, - {_id: 'Video', count: 1}, - ]); + const insertedUser = await users.findOne({_id: 'some-user-id'}); + expect(insertedUser).toEqual(mockUser); + }); }); ``` + +There's no need to load any dependencies. + +See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc). diff --git a/website/versioned_docs/version-23.x/MongoDB.md b/website/versioned_docs/version-23.x/MongoDB.md index 9606b0f9eb3f..df779d2b6b2b 100644 --- a/website/versioned_docs/version-23.x/MongoDB.md +++ b/website/versioned_docs/version-23.x/MongoDB.md @@ -6,140 +6,57 @@ original_id: mongodb With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). -## A jest-mongodb example +## Use jest-mongodb Preset -The basic idea is to: +[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB. -1. Spin up in-memory mongodb server -2. Export a global variable with mongo URI -3. Write tests for queries / aggregations using a real database ✨ -4. Shut down mongodb server using Global Teardown +1. First install `@shelf/jest-mongodb` -Here's an example of the GlobalSetup script - -```js -// setup.js -const path = require('path'); - -const fs = require('fs'); - -const {MongoMemoryServer} = require('mongodb-memory-server'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -const mongod = new MongoMemoryServer({ - autoStart: false, -}); - -module.exports = async () => { - if (!mongod.isRunning) { - await mongod.start(); - } - - const mongoConfig = { - mongoDBName: 'jest', - mongoUri: await mongod.getConnectionString(), - }; - - // Write global config to disk because all tests run in different contexts. - fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig)); - - // Set reference to mongod in order to close the server during teardown. - global.__MONGOD__ = mongod; -}; +``` +yarn add @shelf/jest-mongodb --dev ``` -Then we need a custom Test Environment for Mongo - -```js -// mongo-environment.js -const NodeEnvironment = require('jest-environment-node'); - -const path = require('path'); - -const fs = require('fs'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -class MongoEnvironment extends NodeEnvironment { - constructor(config) { - super(config); - } - - async setup() { - console.log('Setup MongoDB Test Environment'); - - const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8')); - - this.global.__MONGO_URI__ = globalConfig.mongoUri; - this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName; - - await super.setup(); - } - - async teardown() { - console.log('Teardown MongoDB Test Environment'); - - await super.teardown(); - } +2. Specify preset in your Jest configuration: - runScript(script) { - return super.runScript(script); - } +```json +{ + "preset": "@shelf/jest-mongodb" } ``` -Finally we can shut down mongodb server +3. Write your test ```js -// teardown.js -module.exports = async function() { - await global.__MONGOD__.stop(); -}; -``` +const {MongoClient} = require('mongodb'); -With all the things set up, we can now write our tests like this: +describe('insert', () => { + let connection; + let db; -```js -// test.js -const {MongoClient} = require('mongodb'); + beforeAll(async () => { + connection = await MongoClient.connect(global.__MONGO_URI__, { + useNewUrlParser: true, + }); + db = await connection.db(global.__MONGO_DB_NAME__); + }); -let connection; -let db; + afterAll(async () => { + await connection.close(); + await db.close(); + }); -beforeAll(async () => { - connection = await MongoClient.connect(global.__MONGO_URI__); - db = await connection.db(global.__MONGO_DB_NAME__); -}); + it('should insert a doc into collection', async () => { + const users = db.collection('users'); -afterAll(async () => { - await connection.close(); - await db.close(); -}); + const mockUser = {_id: 'some-user-id', name: 'John'}; + await users.insertOne(mockUser); -it('should aggregate docs from collection', async () => { - const files = db.collection('files'); - - await files.insertMany([ - {type: 'Document'}, - {type: 'Video'}, - {type: 'Image'}, - {type: 'Document'}, - {type: 'Image'}, - {type: 'Document'}, - ]); - - const topFiles = await files - .aggregate([ - {$group: {_id: '$type', count: {$sum: 1}}}, - {$sort: {count: -1}}, - ]) - .toArray(); - - expect(topFiles).toEqual([ - {_id: 'Document', count: 3}, - {_id: 'Image', count: 2}, - {_id: 'Video', count: 1}, - ]); + const insertedUser = await users.findOne({_id: 'some-user-id'}); + expect(insertedUser).toEqual(mockUser); + }); }); ``` + +There's no need to load any dependencies. + +See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc). diff --git a/website/versioned_docs/version-24.0/MongoDB.md b/website/versioned_docs/version-24.0/MongoDB.md index dc1f02ff4c14..23ba1283162e 100644 --- a/website/versioned_docs/version-24.0/MongoDB.md +++ b/website/versioned_docs/version-24.0/MongoDB.md @@ -6,142 +6,57 @@ original_id: mongodb With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). -## A jest-mongodb example +## Use jest-mongodb Preset -The basic idea is to: +[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB. -1. Spin up in-memory mongodb server -2. Export a global variable with mongo URI -3. Write tests for queries / aggregations using a real database ✨ -4. Shut down mongodb server using Global Teardown +1. First install `@shelf/jest-mongodb` -Here's an example of the GlobalSetup script - -```js -// setup.js -const path = require('path'); - -const fs = require('fs'); - -const {MongoMemoryServer} = require('mongodb-memory-server'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -const mongod = new MongoMemoryServer({ - autoStart: false, -}); - -module.exports = async () => { - if (!mongod.isRunning) { - await mongod.start(); - } - - const mongoConfig = { - mongoDBName: 'jest', - mongoUri: await mongod.getConnectionString(), - }; - - // Write global config to disk because all tests run in different contexts. - fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig)); - - // Set reference to mongod in order to close the server during teardown. - global.__MONGOD__ = mongod; -}; +``` +yarn add @shelf/jest-mongodb --dev ``` -Then we need a custom Test Environment for Mongo - -```js -// mongo-environment.js -const NodeEnvironment = require('jest-environment-node'); - -const path = require('path'); - -const fs = require('fs'); - -const globalConfigPath = path.join(__dirname, 'globalConfig.json'); - -class MongoEnvironment extends NodeEnvironment { - constructor(config) { - super(config); - } - - async setup() { - console.log('Setup MongoDB Test Environment'); - - const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8')); - - this.global.__MONGO_URI__ = globalConfig.mongoUri; - this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName; - - await super.setup(); - } - - async teardown() { - console.log('Teardown MongoDB Test Environment'); - - await super.teardown(); - } +2. Specify preset in your Jest configuration: - runScript(script) { - return super.runScript(script); - } +```json +{ + "preset": "@shelf/jest-mongodb" } - -module.exports = MongoEnvironment; ``` -Finally we can shut down mongodb server +3. Write your test ```js -// teardown.js -module.exports = async function() { - await global.__MONGOD__.stop(); -}; -``` +const {MongoClient} = require('mongodb'); -With all the things set up, we can now write our tests like this: +describe('insert', () => { + let connection; + let db; -```js -// test.js -const {MongoClient} = require('mongodb'); + beforeAll(async () => { + connection = await MongoClient.connect(global.__MONGO_URI__, { + useNewUrlParser: true, + }); + db = await connection.db(global.__MONGO_DB_NAME__); + }); -let connection; -let db; + afterAll(async () => { + await connection.close(); + await db.close(); + }); -beforeAll(async () => { - connection = await MongoClient.connect(global.__MONGO_URI__); - db = await connection.db(global.__MONGO_DB_NAME__); -}); + it('should insert a doc into collection', async () => { + const users = db.collection('users'); -afterAll(async () => { - await connection.close(); - await db.close(); -}); + const mockUser = {_id: 'some-user-id', name: 'John'}; + await users.insertOne(mockUser); -it('should aggregate docs from collection', async () => { - const files = db.collection('files'); - - await files.insertMany([ - {type: 'Document'}, - {type: 'Video'}, - {type: 'Image'}, - {type: 'Document'}, - {type: 'Image'}, - {type: 'Document'}, - ]); - - const topFiles = await files - .aggregate([ - {$group: {_id: '$type', count: {$sum: 1}}}, - {$sort: {count: -1}}, - ]) - .toArray(); - - expect(topFiles).toEqual([ - {_id: 'Document', count: 3}, - {_id: 'Image', count: 2}, - {_id: 'Video', count: 1}, - ]); + const insertedUser = await users.findOne({_id: 'some-user-id'}); + expect(insertedUser).toEqual(mockUser); + }); }); ``` + +There's no need to load any dependencies. + +See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc).