diff --git a/packages/mongodb-memory-server-core/src/util/MongoInstance.ts b/packages/mongodb-memory-server-core/src/util/MongoInstance.ts index 1d159b7a5..272f9c5d2 100644 --- a/packages/mongodb-memory-server-core/src/util/MongoInstance.ts +++ b/packages/mongodb-memory-server-core/src/util/MongoInstance.ts @@ -13,7 +13,12 @@ import { import { lt } from 'semver'; import { EventEmitter } from 'events'; import { MongoClient, MongoClientOptions, MongoNetworkError } from 'mongodb'; -import { KeyFileMissingError, StartBinaryFailedError, StdoutInstanceError } from './errors'; +import { + GenericMMSError, + KeyFileMissingError, + StartBinaryFailedError, + StdoutInstanceError, +} from './errors'; // ignore the nodejs warning for coverage /* istanbul ignore next */ @@ -327,6 +332,13 @@ export class MongoInstance extends EventEmitter implements ManagerBase { */ async start(): Promise { this.debug('start'); + + if (!isNullOrUndefined(this.mongodProcess?.pid)) { + throw new GenericMMSError( + `Cannot run "MongoInstance.start" because "mongodProcess.pid" is still defined (pid: ${this.mongodProcess?.pid})` + ); + } + this.isInstancePrimary = false; this.isInstanceReady = false; this.isReplSet = false; diff --git a/packages/mongodb-memory-server-core/src/util/__tests__/MongoInstance.test.ts b/packages/mongodb-memory-server-core/src/util/__tests__/MongoInstance.test.ts index 3a30e0bef..5be65f2e6 100644 --- a/packages/mongodb-memory-server-core/src/util/__tests__/MongoInstance.test.ts +++ b/packages/mongodb-memory-server-core/src/util/__tests__/MongoInstance.test.ts @@ -4,7 +4,7 @@ import * as dbUtil from '../utils'; import MongodbInstance, { MongoInstanceEvents } from '../MongoInstance'; import resolveConfig, { ResolveConfigVariables } from '../resolveConfig'; import getPort from 'get-port'; -import { StartBinaryFailedError, StdoutInstanceError } from '../errors'; +import { GenericMMSError, StartBinaryFailedError, StdoutInstanceError } from '../errors'; import { assertIsError } from '../../__tests__/testUtils/test_utils'; jest.setTimeout(100000); // 10s @@ -506,4 +506,28 @@ describe('MongodbInstance', () => { }); }); }); + + it('should throw error if instance is already started (#662)', async () => { + const gotPort = await getPort(); + const mongod = await MongodbInstance.create({ + instance: { port: gotPort, dbPath: tmpDir.name }, + binary: { version }, + }); + + try { + await mongod.start(); + + fail('Expected to Fail'); + } catch (err) { + expect(err).toBeInstanceOf(GenericMMSError); + assertIsError(err); // has to be used, because there is not typeguard from "expect(variable).toBeInstanceOf" + expect( + err.message.includes( + 'Cannot run "MongoInstance.start" because "mongodProcess.pid" is still defined' + ) + ).toBeTruthy(); + } finally { + await mongod.stop(); + } + }); });