I am new to unit testing using Mocha and Chai. I am trying to implement the unit testing on a REST-API which is written using Node.js and MongoDB. I have tried one tutorial but I'm getting AssertionError: expected { Object (driver, name, ...) } to have property '_id' when I run npm test. Mainly it should enter the data into MongoDB.
app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const Note = require('./db/models/note.js').Note;
app.use(bodyParser.json());
app.get('/notes', (req, res) => {
Note.find()
.then((notes) => res.status(200).send(notes))
.catch((err) => res.status(400).send(err));
});
app.post('/notes', (req, res) => {
const body = req.body;
const note = new Note({
name: body.name,
text: body.text
});
note.save(note)
.then((note) => res.status(201).send(note))
.catch((err) => res.status(400).send(err));
});
module.exports = app;
test.js
process.env.NODE_ENV = 'test';
const expect = require('chai').expect;
const request = require('supertest');
const app = require('../../../app.js');
const conn = require('../../../db/index.js');
describe('POST /notes', () => {
before((done) => {
conn.connect()
.then(() => done())
.catch((err) => done(err));
})
after((done) => {
conn.close()
.then(() => done())
.catch((err) => done(err));
})
it('OK, creating a new note works', (done) => {
request(app).post('/notes')
.send({ name: 'NOTE Name', text: "AAA" })
.then((res) => {
const body = res.body;
expect(body).to.contain.property('_id');
expect(body).to.contain.property('name');
expect(body).to.contain.property('text');
done();
})
.catch((err) => done(err));
})
it('Fail, note requires text', (done) => {
request(app).post('/notes')
.send({ name: 'NOTE' })
.then((res) => {
const body = res.body;
expect(body.errors.text.name)
.to.equal('ValidatorError')
done();
})
.catch((err) => done(err));
});
})
The res.body in the test request does not contain a property _id.
The res.body in the test could be debugged/logged in order to find out what the note object looks like. Does the promise return an object at all? If so, does it contain an _id property? The test can be altered accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With