UNPKG

1.74 kBMarkdownView Raw
1# jest-mongodb [![CircleCI](https://circleci.com/gh/shelfio/jest-mongodb/tree/master.svg?style=svg)](https://circleci.com/gh/shelfio/jest-mongodb/tree/master) ![](https://img.shields.io/badge/code_style-prettier-ff69b4.svg) [![npm (scoped)](https://img.shields.io/npm/v/@shelf/jest-mongodb.svg)](https://www.npmjs.com/package/@shelf/jest-mongodb)
2
3> Jest preset to run MongoDB memory server
4
5## Usage
6
7### 0. Install
8
9```
10$ yarn add @shelf/jest-mongodb --dev
11```
12
13### 1. Create `jest.config.js`
14
15```js
16module.exports = {
17 preset: '@shelf/jest-mongodb'
18};
19```
20
21### 2. Create `jest-mongodb-config.js`
22
23See [mongodb-memory-server](https://github.com/nodkz/mongodb-memory-server#available-options)
24
25```js
26module.exports = {
27 mongodbMemoryServerOptions: {
28 instance: {
29 dbName: 'jest'
30 },
31 binary: {
32 version: '3.6.10',
33 skipMD5: true
34 },
35 autoStart: false
36 }
37};
38```
39
40### 3. Configure MongoDB client
41
42```js
43const {MongoClient} = require('mongodb');
44
45let connection;
46let db;
47
48beforeAll(async () => {
49 connection = await MongoClient.connect(global.__MONGO_URI__, {useNewUrlParser: true});
50 db = await connection.db(global.__MONGO_DB_NAME__);
51});
52
53afterAll(async () => {
54 await connection.close();
55 await db.close();
56});
57```
58
59### 4. PROFIT! Write tests
60
61```js
62it('should insert a doc into collection', async () => {
63 const users = db.collection('users');
64
65 const mockUser = {_id: 'some-user-id', name: 'John'};
66 await users.insertOne(mockUser);
67
68 const insertedUser = await users.findOne({_id: 'some-user-id'});
69 expect(insertedUser).toEqual(mockUser);
70});
71```
72
73Cache MongoDB binary in CI by putting this folder to the list of cached paths: `~/.mongodb-binaries`
74
75## License
76
77MIT © [Shelf](https://shelf.io)