Search code examples
javascriptnode.jsexpressjestjsweb-api-testing

Why is this get route , jest test, failing?


Im trying to learn about tdd. And I have written this test

it("should call TodoModel.findById", async () =>{
        await TodoController.getTodoById(req,res,next)
        req.params.todoId = "5f1216dd46a9c73dd812be36"
        expect(TodoModel.findById).toBeCalledWith("5f1216dd46a9c73dd812be36");
    })

For the following function

exports.getTodoById = async (res, req, next) => {
    const todoById = await TodoModel.findById(req.params.todoId)
}

But I keep getting

● TodoController.getTodoById › should call 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)

Why is that happening? Im defining it in the test with a premade id. It should be defined afaik


Solution

  • You see first parameter in your function is always req so change your function to below

    exports.getTodoById = async (req, res, next) => {
        const todoById = await TodoModel.findById(req.params.todoId)
    }