Skip to content

Commit b05ec44

Browse files
committed
feat(MongoMemoryServer): change more errors to "StateError" & more consistent logs
- change more errors to "StateError" - more consistent logs - more comments - small consistency changes
1 parent 64780ee commit b05ec44

File tree

3 files changed

+30
-12
lines changed

3 files changed

+30
-12
lines changed

packages/mongodb-memory-server-core/src/MongoMemoryServer.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
authDefault,
1010
statPath,
1111
} from './util/utils';
12-
import MongoInstance, { MongodOpts, MongoMemoryInstanceOpts } from './util/MongoInstance';
12+
import { MongoInstance, MongodOpts, MongoMemoryInstanceOpts } from './util/MongoInstance';
1313
import { MongoBinaryOpts } from './util/MongoBinary';
1414
import debug from 'debug';
1515
import { EventEmitter } from 'events';
@@ -205,8 +205,6 @@ export class MongoMemoryServer extends EventEmitter {
205205

206206
/**
207207
* Create an Mongo-Memory-Sever Instance
208-
*
209-
* Note: because of JavaScript limitations, autoStart cannot be awaited here, use ".create" for async/await ability
210208
* @param opts Mongo-Memory-Sever Options
211209
*/
212210
constructor(opts?: MongoMemoryServerOpts) {
@@ -243,6 +241,7 @@ export class MongoMemoryServer extends EventEmitter {
243241
/**
244242
* Start the in-memory Instance
245243
* @param forceSamePort Force to use the Same Port, if already an "instanceInfo" exists
244+
* @throws if state is not "new" or "stopped"
246245
*/
247246
async start(forceSamePort: boolean = false): Promise<boolean> {
248247
log('start: Called .start() method');
@@ -254,7 +253,10 @@ export class MongoMemoryServer extends EventEmitter {
254253
case MongoMemoryServerStates.running:
255254
case MongoMemoryServerStates.starting:
256255
default:
257-
throw new Error('Already in state running/starting or unknown');
256+
throw new StateError(
257+
[MongoMemoryServerStates.new, MongoMemoryServerStates.stopped],
258+
this.state
259+
);
258260
}
259261

260262
if (!isNullOrUndefined(this._instanceInfo?.instance.childProcess)) {
@@ -297,7 +299,7 @@ export class MongoMemoryServer extends EventEmitter {
297299

298300
// only log this message if an custom port was provided
299301
if (port != newPort && typeof port === 'number') {
300-
log(`getNewPort: starting with port ${newPort}, since ${port} was locked`);
302+
log(`getNewPort: starting with port "${newPort}", since "${port}" was locked`);
301303
}
302304

303305
return newPort;
@@ -316,7 +318,7 @@ export class MongoMemoryServer extends EventEmitter {
316318
let isNew: boolean = true;
317319

318320
const data: StartupInstanceData = {
319-
port: await this.getNewPort(instOpts.port ?? undefined), // do (null or undefined) to undefined
321+
port: await this.getNewPort(instOpts.port),
320322
dbName: generateDbName(instOpts.dbName),
321323
ip: instOpts.ip ?? '127.0.0.1',
322324
storageEngine: instOpts.storageEngine ?? 'ephemeralForTest',
@@ -337,7 +339,7 @@ export class MongoMemoryServer extends EventEmitter {
337339

338340
isNew = true; // just to ensure "isNew" is "true" because an new temporary directory got created
339341
} else {
340-
log(`Checking if "${data.dbPath}}" (no new tmpDir) already has data`);
342+
log(`getStartOptions: Checking if "${data.dbPath}}" (no new tmpDir) already has data`);
341343
const files = await fspromises.readdir(data.dbPath);
342344

343345
isNew = files.length > 0; // if there already files in the directory, assume that the database is not new
@@ -600,7 +602,15 @@ export class MongoMemoryServer extends EventEmitter {
600602
})
601603
);
602604
default:
603-
throw new Error(`"ensureInstance" does not have an case for "${this._state}"`);
605+
throw new StateError(
606+
[
607+
MongoMemoryServerStates.running,
608+
MongoMemoryServerStates.new,
609+
MongoMemoryServerStates.stopped,
610+
MongoMemoryServerStates.starting,
611+
],
612+
this.state
613+
);
604614
}
605615

606616
log('ensureInstance: no running instance, calling `start()` command');
@@ -638,7 +648,6 @@ export class MongoMemoryServer extends EventEmitter {
638648
* Create Users and restart instance to enable auth
639649
* This Function assumes "this.opts.auth" is defined / enabled
640650
* @param data Used to get "ip" and "port"
641-
*
642651
* @internal
643652
*/
644653
async createAuth(data: StartupInstanceData): Promise<void> {

packages/mongodb-memory-server-core/src/__tests__/MongoMemoryServer.test.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,8 @@ describe('MongoMemoryServer', () => {
272272
await mongoServer.start();
273273
fail('Expected "start" to fail');
274274
} catch (err) {
275-
expect(err.message).toEqual('Already in state running/starting or unknown');
275+
expect(err).toBeInstanceOf(StateError);
276+
expect(err.message).toMatchSnapshot();
276277
}
277278
}
278279

@@ -284,7 +285,8 @@ describe('MongoMemoryServer', () => {
284285
await mongoServer.start();
285286
fail('Expected "start" to fail');
286287
} catch (err) {
287-
expect(err.message).toEqual('Already in state running/starting or unknown');
288+
expect(err).toBeInstanceOf(StateError);
289+
expect(err.message).toMatchSnapshot();
288290
}
289291
}
290292
});
@@ -346,7 +348,8 @@ describe('MongoMemoryServer', () => {
346348
await mongoServer.ensureInstance();
347349
fail('Expected "ensureInstance" to throw');
348350
} catch (err) {
349-
expect(err.message).toEqual('"ensureInstance" does not have an case for "not Existing"');
351+
expect(err).toBeInstanceOf(StateError);
352+
expect(err.message).toMatchSnapshot();
350353
}
351354
});
352355

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
11
// Jest Snapshot v1, https://goo.gl/fbAQLP
22

33
exports[`MongoMemoryServer cleanup() should throw an error if state is not "stopped" 1`] = `"Incorrect State for operation: \\"new\\", allowed States: \\"[stopped]\\""`;
4+
5+
exports[`MongoMemoryServer ensureInstance() should throw an error if the given "_state" has no case 1`] = `"Incorrect State for operation: \\"not Existing\\", allowed States: \\"[running,new,stopped,starting]\\""`;
6+
7+
exports[`MongoMemoryServer start() should throw an error if state is not "new" or "stopped" 1`] = `"Incorrect State for operation: \\"starting\\", allowed States: \\"[new,stopped]\\""`;
8+
9+
exports[`MongoMemoryServer start() should throw an error if state is not "new" or "stopped" 2`] = `"Incorrect State for operation: \\"running\\", allowed States: \\"[new,stopped]\\""`;

0 commit comments

Comments
 (0)