Search code examples
javascriptnode.jsexpressmongoosesupertest

Why is response coming through in Postman working but not my test?


I have this express controller in order to find the amount of unread notifications, that a user is a recipient of. Here:

app.get('/api/user/:uid/notifications/newcount', (req, res, next) => {
    const firebaseUID = req.params.uid;

    User.findOne({ firebaseUID })
      .select('_id')
      .then(user => Notification.count({
          recipients: { $eq: user._id },
          usersRead: { $ne: user._id }
        })
      )
      .then(notificationCount => {
        console.log(notificationCount.toString());
        return res.send(notificationCount.toString())
      })
      .catch(next);
  });

This works just fine in postman.

I am trying to test it with Mocha/Supertest. Yet for some reason, the res.body always come back as an empty object.

The console logs in the actual controller always come through just fine though.

If I don't send as toString() in the res.send(), then I get errors.

res.body should be coming back as 1.

How can I grab the res.body in the below test in order to make an assertion?

it.only('GET to /api/user/firebaseUID/notifications/newcount, gets users unread notifications',
  done => {
      request(app)
        .get(`/api/user/${matt.firebaseUID}/notifications/newcount`)
        .end((err, res) => {
          console.log(res.body);

          done();
        });
  });

Thanks!


Solution

  • In the superagent module that supertest is based on, the response.body property is only populated when the response can be parsed into a Javascript Object. The response.text property will include the plain response body as a string.

    The text property comes from responseText in XMLHttpRequest.