>问题似乎是重复的,但我从过去 3 小时开始一直在努力解决这个问题。基本上,我正在使用supertest
&mocha
来测试我的API。 我无法理解哪个承诺没有得到解决。
app.post('/todos', (req, res) => {
var todo = new Todo({
text : req.body.text
});
todo.save().then( (doc) => {
res.status(200).send(doc)
}, (e) => {
res.status(400).end(e);
});
});
以下是我写的测试:
const expect = require('expect');
const request = require('supertest');
var {app} = require('./../server');
var {Todo} = require('./../models/todo');
// Setup database
beforeEach((done) => {
Todo.remove({})
.then(() => done())
.catch((e)=> done(e));
});
describe('Post /todos', () => {
it('should create a new todo', (done) => {
var text = 'Testing text';
// supertest to get, post
request(app)
.post('/todos')
.send({text}) // Automatic conversion to json - ES6
.expect(200) // assertions
.expect((res) => { // custom parsing
expect(res.body.text).toBe(text);
})
.end((err, res) => { // done directly accepted, but rather let's be more precise now - check mongodb
if (err) {
return done(err);
}
Todo.find()
.then((todos) => {
expect(todos.length).toBe(1);
expect(todos[0].text).toBe(text);
done();
})
.catch((e) => done(e));
});
});
});
请帮助解决此问题。 这是整个错误消息:
摩卡服务器/**/*.test.js 侦听端口:3000 发布/待办事项 (节点:1882(未处理的承诺拒绝警告:未处理的承诺拒绝(拒绝 ID:1(:类型错误:第一个参数必须是字符串或缓冲区 (节点:1882([DEP0018]弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。 1(应该创建一个新的待办事项 0 传球(2 秒( 1 失败 1(发布/待办事项应该创建一个新的待办事项: 错误:超时超过 2000 毫秒。对于异步测试和钩子,请确保调用"done((";如果返回承诺,请确保它解决。
express中的end
函数只接受字符串或缓冲区,不接受对象(请参阅 https://expressjs.com/en/api.html#res.end 和 https://nodejs.org/api/http.html#http_response_end_data_encoding_callback(。
但是,看起来todo.save()
调用reject
带有对象,这意味着e
会导致TypeError
。由于这是捕获承诺拒绝的错误,因此该错误包含在Unhandled Promise Rejection
警告中。
假设e
是{ message: "First argument must be a string or Buffer" }
,新代码可以是:
todo.save().then( (doc) => {
res.status(200).send(doc)
}, (e) => {
res.status(400).end(e.message);
});
todo.save()
承诺被拒绝的原因可能是因为待办事项中的text
似乎未定义。这是分配给req
的 JSON:
{
text: 'Testing text'
}
但是,它应该是这样的:
{
body: {
text: 'Testing text'
}
}
然后,如果您将发送更改为以下内容,则应修复测试:
.send({ body: { text }) // Automatic conversion to json - ES6