Skip to content

Commit

Permalink
Simplify mongodb example by using preset (#8318)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
vladgolubev authored and SimenB committed Apr 18, 2019
1 parent 5a66bbb commit cd415e7
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 358 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down
155 changes: 35 additions & 120 deletions docs/MongoDB.md
Expand Up @@ -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).
153 changes: 35 additions & 118 deletions website/versioned_docs/version-23.x/MongoDB.md
Expand Up @@ -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).

0 comments on commit cd415e7

Please sign in to comment.