-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
76 lines (65 loc) · 2.08 KB
/
index.ts
File metadata and controls
76 lines (65 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import * as fs from 'fs';
import { Db, MongoClient } from 'mongodb';
import * as path from 'path';
import * as rmrf from 'rimraf';
const { MongodHelper } = require('mongodb-prebuilt');
const DEFAULT_PORT = 27017;
const host: string = '127.0.0.1';
const dbPath: string = path.join(__dirname, '__test-with-mongo-test-db__');
/**
* Simple utility class to allow for easy unit, integration, and component testing
* with mongo. Manages spinning up instances and can delete dbs by name
*/
export class TestWithMongo {
private port: number;
constructor(port?: number) {
this.port = port || DEFAULT_PORT;
}
/**
* runs rm -rf on the directory containing the mongodb
* @returns Promise
*/
public clean(): Promise<any> {
return new Promise((res: Function, rej: Function) => {
rmrf(dbPath, (e: Error) => {
if (e) {
return rej(e);
}
res();
});
});
}
/**
* gets the connection string for the test db with the name dbName
* @param dbName the name of the test db
* @returns connectionString
*/
public getConnectionString(dbName: string): string {
return `mongodb://${host}:${this.port}/${dbName}`;
}
/**
* starts mongod on the port set in the constructor
* @returns Promise
*/
public startMongoServer(): Promise<any> {
const mongoHelper = new MongodHelper(['--port', this.port.toString(), '--dbpath', dbPath]);
return this.clean()
.then(() => fs.mkdirSync(dbPath))
.then(() => mongoHelper.run());
}
/**
* Drops db with name dbName
* @param dbName nane of test db to drop
* @returns Promise
*/
public dropDb(dbName: string): Promise<any> {
let db: Db;
const connectionString = this.getConnectionString(dbName);
return MongoClient.connect(connectionString)
.then((retDb: Db) => {
db = retDb;
})
.then(() => db.dropDatabase())
.then(() => db.close());
}
}