Search code examples
node.jsexpressmocha.jssupertest

Mocha supertest isn't POSTing data


My test looks like:

const request = require('supertest-as-promised')
const app = require('../app')

describe("Basic Authentication with JWT", () => {
  it('Should login properly', function () {
    return request(app)
      .post('/login')
      .field('name', 'myname')
      .field('password', 'password')
      .expect(200)
  });
})

In my app, I have:

  app.post("/login", (req, res) => {
    console.log(req.body)

When I run the app normally, it gets the information properly. When I run the test, it shows as {}

What gives?


Solution

  • Try something like that:

     describe("Basic Authentication with JWT", () => {
          it('Should login properly', function () {
            request(app)
                    .post('/login')
                    .send({
                        name: "test_name",
                        password: "test_password"
                    })
                    .then((res) => {
                        res.statusCode.should.eql(200);
                        done();
                    })
                    .catch(done)
          });
        })