0

I'm trying to cleanup 2 collections before each test. I'm using mocha --watch to rerun tests while editing the test source files. First run always executes as expected, but consecutive runs gives Topology was destroyed error from mongodb(indicated via result of http request).

I am not really sure why deleteMany deletes my inserted object in consecutive runs.

describe('myCollection1 related tests', () => {
    // myCollection1 documents should refer to a valid myCollection2 document.
    var foo;
    const exampleObject = {name: 'TEST OBJECT', attr1: 'TO'};
    beforeEach(() => {
        return Promise.all([
            mongo.db('mydb').collection('myCollection1').deleteMany({}), // clear collection 1
            mongo.db('mydb').collection('myCollection2').deleteMany({}) // clear collection 2
            .then(() => mongo.db('mydb').collection('myCollection2').insertOne(exampleObject) // and add a sample object
            .then((value) => {
                foo = value.ops[0]; // save this as test specific variable so I can use it in my tests.
                return Promise.resolve();
            })),
        ]);
    });

    it('should create a related object', (done) => {
        chai.request(server)
            .post('/api/v1/foos/')
            .send({ related: foo._id })
            .then((res) => {
                res.should.have.status(200);
                res.body.should.be.an('object').with.all.keys('status', 'errors', 'data');
                done();
            }).catch((err) => {
                done(err);
        });
    });
});
Yakup Türkan
  • 576
  • 2
  • 6
  • 21

1 Answers1

0

I spotted issue with your promise structure in beforeEach. I'm not sure it is intended or not. I'm afraid it is the culprit. I'm fixing that into below:

  beforeEach(() => {
    return Promise.all([
        mongo.db('mydb').collection('myCollection1').deleteMany({}),
        mongo.db('mydb').collection('myCollection2').deleteMany({})
      ]) // close the promise.all here
      .then(() => collections.engines().insertOne(exampleObject)) // close `then` here
      .then((value) => {
        foo = value.ops[0];
        return Promise.resolve();
      });
  });

Hope it helps

deerawan
  • 8,002
  • 5
  • 42
  • 51
  • Thanks, it was not the culprit :) My intent was clear the collection2 and add a sample object, in both case it does the same thing(just checked to be sure). But this fix an oversight of having another level of indentation. – Yakup Türkan Nov 28 '18 at 21:27
  • I see. I'm looking for `Topology was destroyed` and found this https://stackoverflow.com/questions/30909492/mongoerror-topology-was-destroyed. Have you checked this out? – deerawan Nov 29 '18 at 03:25
  • I was trying to use same connection for tests and api itself. Due to nodejs require caching I was getting already closed connection in my express app. Thanks for the link, I assumed it was trying to read a deleted record. – Yakup Türkan Nov 29 '18 at 05:54