Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify mongodb example by using preset #8318

Merged
merged 6 commits into from Apr 18, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,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).