使用Jest测试Node.js API(和mockgoose)

Coh*_*ars 6 unit-testing mongoose node.js jestjs

这里有两个问题:

1)Jest是测试Node.js(express)API的好选择吗?

2)我正在尝试将Jest与Mockgoose一起使用,但我无法弄清楚如何建立连接并在之后运行测试.这是我在进入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()
}))
Run Code Online (Sandbox Code Playgroud)

错误是Your test suite must contain at least one test.这个错误对我来说有点意义,但我无法弄清楚如何解决它.有什么建议?

输出:

Test suite failed to run

Your test suite must contain at least one test.
Run Code Online (Sandbox Code Playgroud)

Pat*_*ick 1

很晚的回答,但我希望它会有所帮助。如果你注意的话,你的描述块里面没有测试函数。

测试函数实际上是在传递给describe..的回调内部,由于箭头函数回调,堆栈很复杂。

这个示例代码会产生同样的问题..

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);
});
Run Code Online (Sandbox Code Playgroud)

由于与 mongo 的连接是异步的,因此当 jest 第一次扫描函数以在描述中查找“测试”时,它会失败,因为没有。它可能看起来不像,但这正是您正在做的。
我认为在这种情况下你的解决方案有点太聪明了(以至于它不起作用),将其分解为更简单的语句可能有助于查明这个问题