【发布时间】:2018-02-25 21:45:14
【问题描述】:
我正在使用 nodejs 和 mongodb 开发一个小型 todos 应用程序。
我这里有模型定义:
const Todo = new Schema({
text: {
type: String,
require: true,
minlength: 5,
trim: true
},
completed: {
type: Boolean
},
createdAt: {
type: {type: Date, default: Date.now}
}
});
如您所见, text 属性是必需的,如果它在读取请求时丢失,它应该会抛出错误。
在这里,我将数据发送到我的端点:
app.post('/todos', (req, res) => {
let todo = new Todo({
text: req.body.text,
completed: req.body.completed
});
todo.save()
.then((document) => {
res.send(document);
}, (error) => {
res.status(400).send(error);
})
});
最后,这是我对用户向服务器发送空数据集的特定场景的测试:
it('Should not create todo document with invalid body data', (done) => {
request(app)
.post('/todos')
.send({})
.expect(400)
.end((error, res) => {
if(error){
return done(error);
}
Todo.find()
.then((todos) => {
expect(todos.length).toBe(0);
done();
}).catch((error) => done(error));
});
});
运行测试后,由于某种原因,它抛出以下内容:
1) POST /todos
Should not create todo document with invalid body data:
Error: expected 400 "Bad Request", got 200 "OK"
at Test._assertStatus (node_modules\supertest\lib\test.js:266:12)
at Test._assertFunction (node_modules\supertest\lib\test.js:281:11)
at Test.assert (node_modules\supertest\lib\test.js:171:18)
at Server.assert (node_modules\supertest\lib\test.js:131:12)
at emitCloseNT (net.js:1689:8)
at process._tickCallback (internal/process/next_tick.js:152:19)
过去一个小时我一直在尝试调试它,但我找不到它有什么问题。谁能帮帮我?
更新
其他测试:
it('Should create a new todo', (done) => {
let text = 'This is a string';
request(app)
.post('/todos')
.send({text})
.expect(200)
.expect((res) => {
let testString = res.body.text;
expect(testString).toBe(text);
expect(typeof testString).toBe('string');
expect(testString.length).not.toBe(0);
})
.end((error, res) => {
if(error) {
return done(error);
}
Todo.find()
.then((todos) => {
expect(todos.length).toBe(1);
expect(todos[0].text).toBe(text);
done();
}).catch((error) => done(error));
});
});
【问题讨论】:
标签: node.js mocha.js jestjs supertest