UNPKG

1.54 kBJavaScriptView Raw
1const fs = require('fs');
2const {join} = require('path');
3const {MongoMemoryServer, MongoMemoryReplSet} = require('mongodb-memory-server');
4const {
5 getMongodbMemoryOptions,
6 getMongoURLEnvName,
7 shouldUseSharedDBForAllJestWorkers,
8} = require('./helpers');
9
10const debug = require('debug')('jest-mongodb:setup');
11const mongoMemoryServerOptions = getMongodbMemoryOptions();
12const isReplSet = Boolean(mongoMemoryServerOptions.replSet);
13
14debug(`isReplSet ${isReplSet}`);
15
16const mongo = isReplSet
17 ? new MongoMemoryReplSet(mongoMemoryServerOptions)
18 : new MongoMemoryServer(mongoMemoryServerOptions);
19
20const cwd = process.cwd();
21const globalConfigPath = join(cwd, 'globalConfig.json');
22
23module.exports = async () => {
24 const options = getMongodbMemoryOptions();
25 const mongoConfig = {};
26
27 debug(`shouldUseSharedDBForAllJestWorkers: ${shouldUseSharedDBForAllJestWorkers()}`);
28
29 // if we run one mongodb instance for all tests
30 if (shouldUseSharedDBForAllJestWorkers()) {
31 if (!mongo.isRunning) {
32 await mongo.start();
33 }
34
35 const mongoURLEnvName = getMongoURLEnvName();
36
37 mongoConfig.mongoUri = await mongo.getUri();
38
39 process.env[mongoURLEnvName] = mongoConfig.mongoUri;
40
41 // Set reference to mongod in order to close the server during teardown.
42 global.__MONGOD__ = mongo;
43 }
44
45 mongoConfig.mongoDBName = options.instance.dbName;
46
47 // Write global config to disk because all tests run in different contexts.
48 fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));
49 debug('Config is written');
50};