Javascript 断言错误:预期{Object(driver,name,…}具有属性'_id';
我不熟悉使用Mocha和Chai进行单元测试。我试图在REST-API上实现单元测试,该API是使用Node.js和MongoDB编写的。我尝试了一个教程,但我得到了Javascript 断言错误:预期{Object(driver,name,…}具有属性'_id';,javascript,node.js,mocha.js,chai,Javascript,Node.js,Mocha.js,Chai,我不熟悉使用Mocha和Chai进行单元测试。我试图在REST-API上实现单元测试,该API是使用Node.js和MongoDB编写的。我尝试了一个教程,但我得到了AssertionError:当我运行npm测试时,{Object(driver,name,…)}应该有属性“\u id”。主要是将数据输入MongoDB app.js const express = require('express'); const bodyParser = require('body-parser'); con
AssertionError:当我运行npm测试时,{Object(driver,name,…)}应该有属性“\u id”
。主要是将数据输入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));
});
})
测试请求中的res.body
不包含属性\u id
。
可以调试/记录测试中的res.body
,以了解Notes对象的外观。承诺是否返回了一个对象?如果是,它是否包含\u id
属性?可以相应地更改测试。如果您只需删除以下行,错误将消失:expect(body).to.contain.property(“u id”);我已经试过了,但是我给“text”一个和“AssertionError:expected{Object(driver,name,…)}有属性'text'”一样的问题。你能在测试中调试/log到res.body并共享它吗?使用.end()而不是.then(),或者在请求之前的当前代码中使用return
语句。请检查supertest
的文档。谢谢你的帮助,但还是有问题,不过我认为这是一些问题,我的目的,我必须改变一些代码和使用,正如你上面提到的。