这里有两个问题:
1) Jest是测试Node.js (express) API的好选择吗?
2)我正在尝试在Mockgoose中使用Jest,但是我不知道如何建立连接并在之后运行测试。这是我在开始之前的最后一次尝试,所以:
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()
}))错误是Your test suite must contain at least one test。这个错误对我来说有点道理,但我不知道如何解决它。有什么建议吗?
输出:
Test suite failed to run
Your test suite must contain at least one test.发布于 2017-07-06 20:59:48
回答得太晚了,但我希望它能有所帮助。如果您注意到,describe块中没有test函数。
测试函数实际上位于传递给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第一次扫描函数以查找describe中的“test”时,它会失败,因为没有“test”。它可能看起来不像,但这正是您正在做的。
我认为在这种情况下,您的解决方案有点太聪明了(到了不起作用的程度),将其分解为更简单的语句可能有助于查明这个问题
发布于 2018-10-09 20:39:32
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测试代码..using jest我们可以将名称存储在数据库中
https://stackoverflow.com/questions/39532141
复制相似问题