question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Windows] Jest Teardown Unhandled Error. MongoNetworkError: read ECONNRESET

See original GitHub issue

Hi there,

I’m trying to run a typescript + jest + mongodb-memory-server test environment but I’m getting the following error at teardown:

events.js:189
    throw err; // Unhandled 'error' event
    ^

Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET
    at Socket.<anonymous> (C:\Plataforma\Estrutura\Final\node_modules\mongodb\lib\core\connection\connection.js:321:24)
    at Object.onceWrapper (events.js:286:20)
    at Socket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  syscall: 'read',
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} })
    at Connection.emit (events.js:187:17)
    at Socket.<anonymous> (C:\Plataforma\Estrutura\Final\node_modules\mongodb\lib\core\connection\connection.js:321:10)
    at Object.onceWrapper (events.js:286:20)
    at Socket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
error Command failed with exit code 1.

Here are my config files:

//jest.config.js
module.exports = {
  globalSetup: './setup',
  globalTeardown: './teardown.js',
  testEnvironment: './mongo-environment.js',
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.ts?$': 'ts-jest',
  },
  roots: ['<rootDir>/test'],
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
  preset: 'ts-jest',
};
//setup.js
const path = require('path');
const fs = require('fs');
const MongodbMemoryServer = require('mongodb-memory-server');

const globalConfigPath = path.join(__dirname, 'globalConfig.json');

const mongod = new MongodbMemoryServer.default({
    instance: {
        dbName: 'StructureGenerator',
        debug: true,
    },
    binary: {
        version: '3.2.18',
    }
});

module.exports = async function () {
    const mongoConfig = {
        mongoDBName: 'StructureGenerator',
        mongoUri: await mongod.getConnectionString(),
    };

    // Write global config to disk because all tests run in different contexts.
    fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));
    console.log('Config is written');

    // Set reference to mongod in order to close the server during teardown.
    global.MONGOD = mongod;
    process.env.MONGO_URL = mongoConfig.mongoUri;
};
//teardown.js
module.exports = async function () {
  await global.MONGOD.stop();
};
 //mongo-environment.js
const NodeEnvironment = require('jest-environment-node');
const path = require('path');
const fs = require('fs');

const globalConfigPath = path.join(__dirname, 'globalConfig.json');

module.exports = class MongoEnvironment extends NodeEnvironment {
    constructor(config) {
        super(config);
    }

    async setup() {
        console.log('Setup MongoDB Test Environment');
        await super.setup();

        const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8'));

        this.global.MONGO_URI = globalConfig.mongoUri;
        this.global.MONGO_DB_NAME = globalConfig.mongoDBName;

    }

    async teardown() {
        console.log('Teardown MongoDB Test Environment');
        await super.teardown();
    }

    runScript(script) {
        return super.runScript(script);
    }
};

I tried to find help on google but I didn’t manage to find any similar issues. I’m not sure if the problem is related to this package or some of the other ones, but I’m hoping someone can shed me some light on this issue.

Thanks

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:9

github_iconTop GitHub Comments

1reaction
DiegoVictorcommented, Jan 22, 2020

I fix it here by disconnecting Mongoose in every test file and after all tests run:

import Mongoose from 'mongoose';
import app from '../../src/app';

describe('Test', () => {
  afterAll(async () => {
    await Mongoose.disconnect();
  });
  ...

Full example: https://github.com/DiegoVictor/omnistack-8/blob/master/api/__tests__/integration/developer.test.js

I discovered it after enable the debug option. After the tests has been finished the shell showed there were still opened connections.

1reaction
johandavidsoncommented, Sep 10, 2020

I have also this same error. Turns out it could be an issue on Windows machines only (we tested locally on Windows and OSX). I forked this repo and tried the tests and there are a few tests failing on Windows with the same message:

Test Code with debug log
PS C:\Code\Forks\mongodb-memory-server\packages\mongodb-memory-server-core> yarn test
yarn run v1.15.2
$ npm run lint && npm run tscheck && npm run coverage

> mongodb-memory-server-core@6.0.1 tscheck C:\Code\Forks\mongodb-memory-server\packages\mongodb-memory-server-core
> tsc --noEmit


> mongodb-memory-server-core@6.0.1 coverage C:\Code\Forks\mongodb-memory-server\packages\mongodb-memory-server-core
> cross-env MONGOMS_DOWNLOAD_DIR=./tmp jest --coverage

 PASS  src/util/__tests__/resolve-config-test.ts
 PASS  src/util/__tests__/MongoBinaryDownloadUrl-test.ts (5.855s)
  ● Console

    console.warn src/util/MongoBinaryDownloadUrl.ts:7996
      Unknown linux distro Gentoo Linux, falling back to legacy MongoDB build

 PASS  src/util/__tests__/MongoBinary-test.ts (5.978s)
 PASS  src/util/__tests__/MongoBinaryDownload-test.ts (7.11s)
 PASS  src/__tests__/MongoMemoryServer-test.ts (65.847s)
 PASS  src/__tests__/singleDB-test.ts (60.033s)
  ● Console

    console.error ../../node_modules/jest-jasmine2/build/jasmine/Env.js:289
      Unhandled error
    console.error ../../node_modules/jest-jasmine2/build/jasmine/Env.js:290
      Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET
          at Socket.<anonymous> (C:\Code\Forks\mongodb-memory-server\node_modules\mongodb\lib\core\connection\connection.js:325:24)
          at Object.onceWrapper (events.js:286:20)
          at Socket.emit (events.js:198:13)
          at emitErrorNT (internal/streams/destroy.js:91:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)
        errno: 'ECONNRESET',
        code: 'ECONNRESET',
        syscall: 'read',
        name: 'MongoNetworkError',
        errorLabels: [ 'TransientTransactionError' ],
        [Symbol(mongoErrorContextSymbol)]: {} })
          at Connection.emit (events.js:187:17)
          at Socket.<anonymous> (C:\Code\Forks\mongodb-memory-server\node_modules\mongodb\lib\core\connection\connection.js:325:10)
          at Object.onceWrapper (events.js:286:20)
          at Socket.emit (events.js:198:13)
          at emitErrorNT (internal/streams/destroy.js:91:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)

 PASS  src/__tests__/multipleDB-test.ts (66.669s)
  ● Console

    console.error ../../node_modules/jest-jasmine2/build/jasmine/Env.js:289
      Unhandled error
    console.error ../../node_modules/jest-jasmine2/build/jasmine/Env.js:290
      Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET
          at Socket.<anonymous> (C:\Code\Forks\mongodb-memory-server\node_modules\mongodb\lib\core\connection\connection.js:325:24)
          at Object.onceWrapper (events.js:286:20)
          at Socket.emit (events.js:198:13)
          at emitErrorNT (internal/streams/destroy.js:91:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)
        errno: 'ECONNRESET',
        code: 'ECONNRESET',
        syscall: 'read',
        name: 'MongoNetworkError',
        errorLabels: [ 'TransientTransactionError' ],
        [Symbol(mongoErrorContextSymbol)]: {} })
          at Connection.emit (events.js:187:17)
          at Socket.<anonymous> (C:\Code\Forks\mongodb-memory-server\node_modules\mongodb\lib\core\connection\connection.js:325:10)
          at Object.onceWrapper (events.js:286:20)
          at Socket.emit (events.js:198:13)
          at emitErrorNT (internal/streams/destroy.js:91:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)

 FAIL  src/__tests__/replset-test.ts (61.986s)
  ● multi-member replica set › should enter running state

    : Timeout - Async callback was not invoked within the 40000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 40000ms timeout specified by jest.setTimeout.Error:

       5 | 
       6 | describe('multi-member replica set', () => {
    >  7 |   it('should enter running state', async () => {
         |   ^
       8 |     const opts: any = { replSet: { count: 3 } };
       9 |     const replSet = new MongoMemoryReplSet(opts);
      10 |     await replSet.waitUntilRunning();

      at new Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (src/__tests__/replset-test.ts:7:3)
      at Object.<anonymous> (src/__tests__/replset-test.ts:6:1)

  ● multi-member replica set › should be possible to connect replicaset after waitUntilRunning resolveds

    Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET

      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:24)
        errno: 'ECONNRESET',
        code: 'ECONNRESET',
        syscall: 'read',
        name: 'MongoNetworkError',
        errorLabels: [ 'TransientTransactionError' ],
        [Symbol(mongoErrorContextSymbol)]: {} })
      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:10)

 PASS  src/util/__tests__/MongoInstance-test.ts (68.727s)
  ● Console

    console.log src/util/MongoBinary.ts:6736
      MongoBinary options: {"downloadDir":"./tmp","platform":"win32","arch":"x64","version":"4.0.3","debug":true}
    console.log src/util/MongoBinary.ts:6896
      MongoBinary: Mongod binary path: C:\Code\Forks\mongodb-memory-server\packages\mongodb-memory-server-core\tmp\4.0.3\mongod.exe
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: Called MongoInstance._launchKiller(parent: 27800, child: 18164):
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.001+0100 I CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] MongoDB starting : pid=18164 port=27445 dbpath=C:\Users\JOHAND~1\AppData\Local\Temp\mongo-mem-27800PRBECSrdwgVj 64-bit host=DESKTOP-8IQI084
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] db version v4.0.3
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] git version: 7ea530946fa7880364d88c8d8b6026bbc9ffa48c
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] allocator: tcmalloc
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] modules: none
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] build environment:
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten]     distarch: x86_64
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten]     target_arch: x86_64
      2019-12-02T13:42:50.063+0100 I CONTROL  [initandlisten] options: { net: { bindIp: "127.0.0.1", port: 27445 }, security: { authorization: "disabled" }, storage: { dbPath: "C:\Users\JOHAND~1\AppData\Local\Temp\mongo-mem-27800PRBECSrdwgVj" } }

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.066+0100 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=7642M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress),

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.125+0100 I STORAGE  [initandlisten] WiredTiger message [1575290570:125714][18164:140719549993568], txn-recover: Set global recovery timestamp: 0

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.145+0100 I RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.200+0100 I STORAGE  [initandlisten] createCollection: admin.system.version with provided UUID: 794a0d0f-21cf-40f0-aeed-0433fad7902a

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.235+0100 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 4.0

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.240+0100 I STORAGE  [initandlisten] createCollection: local.startup_log with generated UUID: ca3d0272-7115-47d3-aa37-36fe78b032c5

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.822+0100 W FTDC     [initandlisten] Failed to initialize Performance Counters for FTDC: WindowsPdhError: PdhExpandCounterPathW failed with 'The specified object was not found on the computer.' for counter '\Memory\Available Bytes'

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.822+0100 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/Users/JOHAND~1/AppData/Local/Temp/mongo-mem-27800PRBECSrdwgVj/diagnostic.data'

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: 2019-12-02T13:42:50.824+0100 I STORAGE  [LogicalSessionCacheRefresh] createCollection: config.system.sessions with generated UUID: 7070d4c4-6655-4113-8f66-0ff59efe01ec
      2019-12-02T13:42:50.825+0100 I NETWORK  [initandlisten] waiting for connections on port 27445

    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: MongodbInstance: is ready!
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: Called MongoInstance.kill():
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]:  - childProcess: send kill cmd...
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]:  - childProcess: got exit signal. Ok!
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: CLOSE: null
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]:  - killerProcess: send kill cmd...
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]: [MongoKiller]: exit - [null,"SIGTERM"]
    console.log src/util/MongoInstance.ts:7640
      Mongo[27445]:  - killerProcess: got exit signal. Ok!

 FAIL  src/__tests__/replset-single-test.ts (69.077s)
  ● single server replset › should enter running state

    Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET

      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:24)
        errno: 'ECONNRESET',
        code: 'ECONNRESET',
        syscall: 'read',
        name: 'MongoNetworkError',
        errorLabels: [ 'TransientTransactionError' ],
        [Symbol(mongoErrorContextSymbol)]: {} })
      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:10)

  ● single server replset › should be able to get connection string to specific db

    Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ MongoNetworkError: read ECONNRESET

      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:24)
        errno: 'ECONNRESET',
        code: 'ECONNRESET',
        syscall: 'read',
        name: 'MongoNetworkError',
        errorLabels: [ 'TransientTransactionError' ],
        [Symbol(mongoErrorContextSymbol)]: {} })
      at Socket.<anonymous> (../../node_modules/mongodb/lib/core/connection/connection.js:325:10)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Issue at teardown with Jest + mongodb-memory-server
I'm trying to run a typescript + jest + mongodb-memory-server test environment but I'm getting the following error at teardown:
Read more >
What does “Error: read ECONNRESET” mean? - Quora
It means that your application dropped it's TCP connection. For example, if you lost your wifi signal while running your app you would...
Read more >
NodeJS + MongoDB Error: read ECONNRESET Issue
I know my network is little unstable, but i want to make my mongo driver retry forever how can i make that change?...
Read more >
Npm test - M220JS: MongoDB for Javascript Developers
When I run npm test -t projection, it fails, below is the error message. ... read property 'close' of undefined 17 | 18...
Read more >
Setup and Teardown - Jest
If you have some work you need to do repeatedly for many tests, you can use beforeEach and afterEach hooks. For example, let's...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found