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

6

这里有两个问题:

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()
}))

错误信息是您的测试套件必须至少包含一个测试。这个错误对我来说有点意义,但我不知道该如何解决。有什么建议吗?
Test suite failed to run

Your test suite must contain at least one test.
2个回答

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);
});

由于与Mongo的连接是异步的,当Jest首次扫描函数以查找描述中的“测试”时,它会失败,因为没有找到。看起来可能不像,但这正是你正在做的事情。
我认为在这种情况下,你的解决方案有点过于聪明(甚至不起作用),将其拆分为更简单的语句可能有助于确定问题所在。

-1
    var mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost/animal', { useNewUrlParser: true });

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

    var kittySchema = new mongoose.Schema({
        name: String
      });

      var god = mongoose.model('god', kittySchema);



module.exports = god;

god.js 文件的代码

describe("post api", () => {
  //life cycle hooks for unit testing
  beforeAll(() => {
    mongoose.connect(
      "mongodb://localhost/animal",
      { useNewUrlParser: true }
    );
  });
  //test the api functions
  test("post the data", async () => {
    console.log("inside the test data ");

    var silence = await new god({ name: "bigboss" }).save();

  });
  // disconnecting the mongoose connections
  afterAll(() => {
    // mongoose.connection.db.dropDatabase(function (err) {
    //     console.log('db dropped');
    //   //  process.exit(0);
    //   });
    mongoose.disconnect(done);
  });
});

使用 Jest 进行测试代码...我们可以使用 Jest 将名称存储在数据库中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接