Test Node.js API with Jest (and mockgoose)
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
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;
code for god.js file
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 testing code ..using jest we can we store the name in db