为什么这个 get route , jest test 失败了?
Why is this get route , jest test, failing?
我正在尝试了解 tdd。我已经写了这个测试
it("should call TodoModel.findById", async () =>{
await TodoController.getTodoById(req,res,next)
req.params.todoId = "5f1216dd46a9c73dd812be36"
expect(TodoModel.findById).toBeCalledWith("5f1216dd46a9c73dd812be36");
})
对于以下函数
exports.getTodoById = async (res, req, next) => {
const todoById = await TodoModel.findById(req.params.todoId)
}
但我不断得到
● TodoController.getTodoById › 应该调用 TodoModel.findById
TypeError: Cannot read property 'todoId' of undefined
22 |
23 | exports.getTodoById = async (res, req, next) => {
> 24 | const todoById = await TodoModel.findById(req.params.todoId)
| ^
25 | }
at Object.getTodoById (controllers/todo.controller.js:24:57)
at Object.<anonymous> (tests/unit/todo.controller.test.js:54:30)
为什么会这样?我在测试中使用预制 ID 定义它。它应该被定义为afaik
您看到函数中的第一个参数始终是 req
,因此请将您的函数更改为以下
exports.getTodoById = async (req, res, next) => {
const todoById = await TodoModel.findById(req.params.todoId)
}
我正在尝试了解 tdd。我已经写了这个测试
it("should call TodoModel.findById", async () =>{
await TodoController.getTodoById(req,res,next)
req.params.todoId = "5f1216dd46a9c73dd812be36"
expect(TodoModel.findById).toBeCalledWith("5f1216dd46a9c73dd812be36");
})
对于以下函数
exports.getTodoById = async (res, req, next) => {
const todoById = await TodoModel.findById(req.params.todoId)
}
但我不断得到
● TodoController.getTodoById › 应该调用 TodoModel.findById
TypeError: Cannot read property 'todoId' of undefined
22 |
23 | exports.getTodoById = async (res, req, next) => {
> 24 | const todoById = await TodoModel.findById(req.params.todoId)
| ^
25 | }
at Object.getTodoById (controllers/todo.controller.js:24:57)
at Object.<anonymous> (tests/unit/todo.controller.test.js:54:30)
为什么会这样?我在测试中使用预制 ID 定义它。它应该被定义为afaik
您看到函数中的第一个参数始终是 req
,因此请将您的函数更改为以下
exports.getTodoById = async (req, res, next) => {
const todoById = await TodoModel.findById(req.params.todoId)
}