L
L
Levingstone2020-03-25 15:13:58
Node.js
Levingstone, 2020-03-25 15:13:58

Why does the router fail the jest test for a PUT request, although the data from the test comes to the server?

Hello. Tell me what could be the problem.
I use jest testing. The fact is that the tests throw a 500 error, although the data goes to the database and is published in the application. Along with the server error, it also throws the following error: I am attaching the
code and logs.
Test:

it("Route '/' POST , should post the task", async () => {
    const todo = Todo.create({
      title: "title tests",
      done: false
    });
    return request(app.use(router))
      .post("/")
      .send(todo)
      .set({ "Content-Type": "application/json" })
      .expect(500)
      .then(res => {
        console.log(res.body);
        expect(res.body).toMatchSnapshot();
      });
  });


Error in logs:


console.log src/server/routes/index.js:26
TypeError: Cannot read property 'title' of undefined


The code of the router on which he swears:

router.post("/", async (req, res) => {
  console.log(req.body);
  try {
    const todo = await Todo.create({
      title: req.body.title, //* TypeError: Cannot read property 'title' of undefined *//
      done: false
    });
    res.status(201).json({ todo });
  } catch (error) {
    console.log(error);
    res.status(500).json({
      message: "There is an error on server"
    });
  }
});

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-03-25
@Robur

1. put await before Todo.create.
2. what kind of ORM? you most likely have data "going" to the database because you create it in the test and create writes it to the database. The second create on the server crashes and doesn't actually do anything

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question