Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Node.js API with Jest (and mockgoose)

Two questions here:

1) Is Jest a good options to test Node.js (express) APIs?

2) I'm trying to use Jest with Mockgoose, but I can't figure out how to establish the connection and run tests after. Here is my final attempt before coming on SO:

const Mongoose = require('mongoose').Mongoose
const mongoose = new Mongoose()
mongoose.Promise = require('bluebird')
const mockgoose = require('mockgoose')

const connectDB = (cb) => () => {
  return mockgoose(mongoose).then(() => {
    return mongoose.connect('mongodb://test/testingDB', err => {
      if (err) {
        console.log('err is', err)
        return process.exit()
      }
      return cb(() => {
        console.log('END') // this is logged
        mongoose.connection.close()
      })
    })
  })
}

describe('test api', connectDB((end) => {
  test('adds 1 + 2 to equal 3', () => {
    expect(1 + 2).toBe(3)
  })
  end()
}))

The error is Your test suite must contain at least one test. This error makes a bit of sense to me but I can't figure out how to solve it. Any suggestions?

Output:

Test suite failed to run

Your test suite must contain at least one test.
like image 590
Cohars Avatar asked Sep 16 '16 12:09

Cohars


1 Answers

Very late answer, but I hope it'll help. If you pay attention, your describe block has no test function inside it.

The test function is actually inside the callback passed to describe.. kind of, the stack is complicated due to arrow function callbacks.

this example code will generate the same problem..

describe('tests',function(){
  function cb() {
    setTimeout(function(){
      it('this does not work',function(end){
        end();
      });
    },500);
  }
  cb();

  setTimeout(function(){
    it('also does not work',function(end){
      end();
    });
  },500);
});

since the connection to mongo is async, when jest first scans the function to find "tests" inside the describe, it fails as there is none. it may not look like it, but that's exactly what you're doing.
I think in this case your solution was a bit too clever(to the point it doesn't work), and breaking it down to simpler statements could've helped pinpointing this issue

like image 92
Patrick Avatar answered Oct 03 '22 01:10

Patrick