我是使用Mocha和Chai进行单元测试的新手。我正在尝试在使用Node.js和MongoDB编写的REST-API上实现单元测试。我已经尝试过一个教程,但是运行AssertionError: expected { Object (driver, name, ...) } to have property '_id'
时得到npm test
。主要是应该将数据输入到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));
});
})
答案 0 :(得分:1)
测试请求中的res.body
不包含属性_id
。
可以对测试中的res.body
进行调试/记录,以找出便笺对象的外观。诺言是否会返回对象?如果是这样,它是否包含_id
属性?可以相应地更改测试。