mardi 5 avril 2016

Timeout when attempting to connect to mongo from jest unit tests

I want to write some unit tests with jest and mongoose to validate data interaction with mongo.

I don't want to mock mongoose here because I specifically want to validate the way that mongo documents are created/modified/handled.

package.json is configured to leave node modules unmocked:

{
  "jest": {
    "unmockedModulePathPatterns": [
      "node_modules"
    ]
  }
}

In my actual test, I have set up a beforeAll() hook to take care of connecting to mongo:

const mongoose = require('mongoose');

describe('MyTest', () => {

  beforeAll((done) => {
    mongoose.connect('mongodb://127.0.0.1:27017/test');

    let db = mongoose.connection;

    db.on('error', (err) => {
      done.fail(err);
    });

    db.once('open', () => {
      done();
    });
  });

  it('has some property', () => {
    // should pass but actually never gets run
    expect(1).toBe(1);
  });
});

This test times out every time because done() is never called in the beforeAll() hook - no errors thrown nor anything printed to console. I can place breakpoints in the beforeAll() hook to validate the code is being run. It appears that mongoose is hanging whilst attempting to open a connection to Mongo, and then the jest tests are timing out.

When I'm running similar code outside of the jest environment, it connects as expected (nigh on instantly). Suspecting that it could be causing problems, I've experimented with disabling jest's automock feature completely, but the behaviour remains unchanged.

I imagine I've missed something incredibly obvious... any ideas what could be going on?

jest-cli v. 0.10.0 mongoose v. 4.4.11

Aucun commentaire:

Enregistrer un commentaire