UNPKG

1.17 kBJavaScriptView Raw
1const fs = require('fs');
2const {resolve, join} = require('path');
3const cwd = require('cwd');
4const MongodbMemoryServer = require('mongodb-memory-server');
5const globalConfigPath = join(__dirname, 'globalConfig.json');
6
7const mongod = new MongodbMemoryServer.default(getMongodbMemoryOptions());
8
9module.exports = async () => {
10 if (!mongod.isRunning) {
11 await mongod.start();
12 }
13
14 const mongoConfig = {
15 mongoDBName: 'jest',
16 mongoUri: await mongod.getConnectionString()
17 };
18
19 // Write global config to disk because all tests run in different contexts.
20 fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));
21 console.log('Config is written');
22
23 // Set reference to mongod in order to close the server during teardown.
24 global.__MONGOD__ = mongod;
25 process.env.MONGO_URL = mongoConfig.mongoUri;
26};
27
28function getMongodbMemoryOptions() {
29 try {
30 const {mongodbMemoryServerOptions} = require(resolve(cwd(), 'jest-mongodb-config.js'));
31
32 return mongodbMemoryServerOptions;
33 } catch (e) {
34 return {
35 instance: {
36 dbName: 'jest'
37 },
38 binary: {
39 skipMD5: true
40 },
41 autoStart: false
42 };
43 }
44}