• Stars
    star
    588
  • Rank 75,985 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Jest preset for MongoDB in-memory server

jest-mongodb CircleCI npm (scoped)

Jest preset to run MongoDB memory server

Usage

0. Install

$ yarn add @shelf/jest-mongodb --dev

Make sure mongodb is installed in the project as well, as it's required as a peer dependency.

1. Create jest.config.js

module.exports = {
  preset: '@shelf/jest-mongodb',
};

If you have a custom jest.config.js make sure you remove testEnvironment property, otherwise it will conflict with the preset.

2. Create jest-mongodb-config.js

See mongodb-memory-server

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      version: '4.0.3',
      skipMD5: true,
    },
    autoStart: false,
    instance: {},
  },
};

To use the same database for all tests pass the config like this:

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      version: '4.0.3',
      skipMD5: true,
    },
    instance: {
      dbName: 'jest',
    },
    autoStart: false,
  },
};

To use separate database for each jest worker pass the useSharedDBForAllJestWorkers: false (doesn't create process.env variable when using this option):

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      skipMD5: true,
    },
    autoStart: false,
    instance: {},
  },

  useSharedDBForAllJestWorkers: false,
};

To use dynamic database name you must pass empty object for instance field:

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      version: '4.0.3',
      skipMD5: true,
    },
    instance: {},
    autoStart: false,
  },
};

To use another uri environment variable name you must set mongoURLEnvName field:

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      version: '4.0.3',
      skipMD5: true,
    },
    instance: {},
    autoStart: false,
  },
  mongoURLEnvName: 'MONGODB_URI',
};

To use mongo as a replica set you must add the replSet config object and set count and storageEngine fields:

module.exports = {
  mongodbMemoryServerOptions: {
    binary: {
      skipMD5: true,
    },
    autoStart: false,
    instance: {},
    replSet: {
      count: 3,
      storageEngine: 'wiredTiger',
    },
  },
};

3. Configure MongoDB client

Library sets the process.env.MONGO_URL for your convenience, but using of global.__MONGO_URI__ is preferable as it works with useSharedDBForAllJestWorkers: false

const {MongoClient} = require('mongodb');

describe('insert', () => {
  let connection;
  let db;

  beforeAll(async () => {
    connection = await MongoClient.connect(global.__MONGO_URI__, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    db = await connection.db();
  });

  afterAll(async () => {
    await connection.close();
  });
});

4. PROFIT! Write tests

it('should insert a doc into collection', async () => {
  const users = db.collection('users');

  const mockUser = {_id: 'some-user-id', name: 'John'};
  await users.insertOne(mockUser);

  const insertedUser = await users.findOne({_id: 'some-user-id'});
  expect(insertedUser).toEqual(mockUser);
});

Cache MongoDB binary in CI by putting this folder to the list of cached paths: ./node_modules/.cache/mongodb-memory-server/mongodb-binaries

You can enable debug logs by setting environment variable DEBUG=jest-mongodb:*

5. Clean collections before each test (optional)

beforeEach(async () => {
  await db.collection('COLLECTION_NAME').deleteMany({});
});

See this issue for discussion

6. Jest watch mode gotcha

This package creates the file globalConfig.json in the project root, when using jest --watch flag, changes to globalConfig.json can cause an infinite loop

In order to avoid this unwanted behaviour, add globalConfig to ignored files in watch mode in the Jest configuation

// jest.config.js
module.exports = {
  watchPathIgnorePatterns: ['globalConfig'],
};

See Also

Publish

$ git checkout master
$ yarn version
$ yarn publish
$ git push origin master --tags

License

MIT © Shelf

More Repositories

1

chrome-aws-lambda-layer

58 MB Google Chrome to fit inside AWS Lambda Layer compressed with Brotli
627
star
2

aws-lambda-libreoffice

Utility to work with Docker version of LibreOffice in Lambda
TypeScript
221
star
3

jest-dynamodb

Jest preset for DynamoDB local server
TypeScript
179
star
4

libreoffice-lambda-layer

Shell
109
star
5

ghostscript-lambda-layer

Ghostscript AWS Lambda layer
Shell
93
star
6

aws-lambda-tesseract

6 MB Tesseract (with English training data) to fit inside AWS Lambda
Shell
86
star
7

dynamodb-parallel-scan

Scan large DynamoDB tables faster with parallelism
TypeScript
65
star
8

libreoffice-lambda-base-image

26
star
9

fast-chunk-string

Chunk string into equal substrings with unicode support
TypeScript
18
star
10

tika-text-extract

Extract text from a document by Apache Tika
TypeScript
15
star
11

dynamodb-query-optimized

TypeScript
13
star
12

apache-tika-lambda-layer

AWS Lambda layer containing latest version of Apache Tika
Shell
13
star
13

winston-datadog-logs-transport

Winston transport for Datadog Logs (not events)
JavaScript
13
star
14

java-lambda-layer

AWS Lambda layer with Java 8
Shell
12
star
15

jest-postgres

Jest preset for running tests with local Postgres
TypeScript
10
star
16

aws-ddb-with-xray

AWS DynamoDB Document Client initialized with X-Ray
TypeScript
9
star
17

jest-elasticsearch

Jest preset for running tests with local ElasticSearch
TypeScript
9
star
18

aws-lambda-brotli-unpacker

Unpacks large Lambda binaries to /tmp
TypeScript
9
star
19

fast-natural-order-by

Lightweight (< 2.3kB gzipped) and performant natural sorting of arrays and collections by differentiating between unicode characters, numbers, dates, etc.
TypeScript
8
star
20

es-painless-fields

Generate Painless Elasticsearch script to set / unset fields on document from JavaScript Object
TypeScript
7
star
21

serverless-simplify-default-exec-role-plugin

Fixes "IamRoleLambdaExecution - Maximum policy size of 10240 bytes exceeded" error
JavaScript
7
star
22

fast-normalize-spaces

A faster (by 16-70%) implementation of "normalize-space-x" package that uses at least 3x less RAM
TypeScript
6
star
23

elasticsearch-local

Run any version of ElasticSearch locally
TypeScript
6
star
24

eslint-config

JavaScript
6
star
25

array-chunk-by-size

Chunk array of objects by their size in JSON
TypeScript
4
star
26

postgres-local

Run Postgres locally
TypeScript
4
star
27

jest-testrail-reporter

Simple package to submit jest test results to TestRail
TypeScript
3
star
28

aws-ssm-get-param-cli

Get value of SSM parameter
JavaScript
3
star
29

pspdfkit-ssr

Utilities to work with PSPDFKit's server-side rendering
TypeScript
2
star
30

gh-sdk

Convenient wrapper for GitHub API for automation tasks
TypeScript
2
star
31

react-outside-click

React library for handling outside clicks of a specified element
TypeScript
2
star
32

renovate-config-public

1
star
33

is-string-in-quotes

Check if string is inside quotation marks (21 styles)
TypeScript
1
star
34

fast-normalize-spaces-as

TypeScript
1
star
35

trim-around-tag

Trims text to max length around any HTML tag w/o breaking words
TypeScript
1
star
36

evaluate-expressions

Evaluate expressions that consist of multiple rules and joiners.
TypeScript
1
star
37

datetime

Shelf dates library
TypeScript
1
star
38

text-normalizer

Clone of openai Whisperer text normalization done and tested on Typescript!
TypeScript
1
star
39

table-of-contents

Linkify HTML headers and generate a TOC
TypeScript
1
star
40

image-preview-overlay

TypeScript
1
star