Search code examples
javascripttestingjestjssupertest

Passing request body to post using super-test


I'm testing an express server using super-test and I need to test a post call. I assume the post should be successful and return a status of 200 but it is returning 401. I've been told by someone that I need to pass a request body with the post but I'm unsure exactly how to do this.

I've attempted to use .send({name: 'aName'}) but that gives me the same 401 code.

Below is the app.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const hateoasLinker = require('express-hateoas-links');
const AValidator = require('./AValidator');
const BValidator = require('./BValidator');
const schema_v1 = require("./schema.json");
const {
    logService: logger
} = require("@utils");

let aValidator = AValidator(schema_v1);

let ValidatorApi = BValidator.ValidatorApi('api');
let adminValidator = BValidator.ValidatorAdmin('admin');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(hateoasLinker);

app.post('/*/activate',admiValidator, (req, res) => {
    console.log("In Activate===============>");
    res.status(200);
    res.json({
        rel: "self",
        method: "POST",
        title: 'Activate Solution',
        href: "/activate"
    });
});

Here is the code for the BValidator

ValidatorAdmin = function(callType){
    return function (req,res,next){
        let authoizationHeader = req.headers['authorization'];
        try {
        Verifier.verifyPayload(authoizationHeader, callType, (verificationError) => {
            if (verificationError) {
                res.setHeader('Content-Type', 'application/json');
                res.status(401);
                res.json({
                    message : "verificationError "+verificationError.message
                });
            } else {
                next();
            }
        });
        } catch (authorizationError) {
            res.setHeader('Content-Type', 'application/json');
            res.status(401);
            res.json({
                message : authorizationError.message
            });

        }
    }
}

Here is the app.test.js

const request = require('supertest');
const bodyParser = require('body-parser');
let AValidator = require('../src/AValidator');
let BValidator = require('../src/BValidator');
BValidator = jest.fn();
AValidator = jest.fn();
app = require('../src/app');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

describe('Test os GET/POST calls in app.js', ()=>{

  test('Tests activate post', (done)=>{

    BValidator.mockReturnValue({
      ValidatorApi: (req,res,next)=>{
        next();
      },
      ValidatorAdmin:(req,res,next)=>{
        next();
      }
    });

    AValidator.mockImplementation((schema)=>{
      return function (req,res,next){
        next();
      }
    });


    request(app)
      .post('/test/activate')
      .set({name:'josh'})
      .then((response)=>{
        expect(response.statusCode).toBe(200);
        done();
      })

  })


});

So ultimately I'd like this post to resolve successfully and return a status code of 200.

Solution

  • I am assuming you have set the parser correctly. Example:

     const app = express();
     app.use(bodyParser.json());
     app.use(bodyParser.urlencoded({extended: true}));
    

    Once this is set, I believe you're missing the headers. Example:

    const payload = {name: 'john', email: 'xyz@sadfjak.com', password: '2342388' };
    const res = await request(app)
                .post('/api/register')
                .send(payload)
                .set('Content-Type', 'application/json')
                .set('Accept', 'application/json')