Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  98] [ 3]  / answers: 1 / hits: 5641  / 4 Years ago, thu, january 30, 2020, 12:00:00

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

More From » node.js

 Answers
6

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.


[#4891] Tuesday, January 28, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
Sun, Aug 23, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Wed, Dec 18, 19, 00:00, 5 Years ago
Sat, Sep 21, 19, 00:00, 5 Years ago
;