摩卡 使用超级测试,类型错误:无法读取未定义的属性'call'



我正在学习为我的基本Todo应用程序使用异步测试。但我在为我的应用程序开发测试套件时发现了一个错误

我想使用我的测试套件删除一个todo。

这是我的代码:

app.delete('/todos/:id', (req,res) => {
const id = req.params.id ;
if(!ObjectID.isValid(id))
return res.status(400).send();
Todo.findByIdAndRemove(id)
.then((todo) => {
res.send(todo);
}, (error) => {
res.status(404).send();
});        
});

这是测试套件的代码:

const todos = [{
_id: new ObjectId(),
text: 'first Todo'
},
{
_id: new ObjectId(),
text: 'Second Todo'
}
];
beforeEach((done) => {
Todo.remove({}).then(() => {
return Todo.insertMany(todos);
done();
}).then(() => {
done();
}).catch(e => {
console.log(e);
done();
});
});
describe('DELETE /todos/:id', () => {
it('should delete a todo', (done) => {
request(app)
.delete(`/todos/${todos[1]._id.toHexString()}`)
.expect(200)
.end(done());
});
});

我发现了一个类似的错误:

Uncaught TypeError: Cannot read property 'call' of undefined
at Test.assert (node_modules/supertest/lib/test.js:181:6)
at Server.assert (node_modules/supertest/lib/test.js:131:12)
at emitCloseNT (net.js:1655:8)
at _combinedTickCallback (internal/process/next_tick.js:135:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

感谢

我也遇到了同样的问题。因为使用.end(done(((而不是.end(已完成(这是正确的。

在测试用例完成之前,您正在调用done()。这似乎就是问题所在。

request(app)
.delete(`/todos/${todos[1]._id.toHexString()}`)
.expect(200)
.end(done); // pass the callback, not the result of executing the callback

我想,这是由不整洁的done调用引起的。我的建议是避免done,因为mocha通过指定return到promise函数来支持promise。

我正在帮助您改进代码如下:

const todos = [{
_id: new ObjectId(),
text: 'first Todo'
},
{
_id: new ObjectId(),
text: 'Second Todo'
}
];
beforeEach(() => {
// I removed `done` and add `return` 
return Todo.remove({})
.then(() => {
return Todo.insertMany(todos);
}).catch(e => {
console.log(e);
});
});
describe('DELETE /todos/:id', () => {
it('should delete a todo', () => {
return request(app)
.delete(`/todos/${todos[1]._id.toHexString()}`)
.expect(200);
});
});

它更干净,不是吗?

希望它能帮助

最新更新