Search code examples
javascriptnode.jsjestjscontinuous-integrationtdd

Error sending params with jest in node simulating a form


I'm using jest to make my CI tests, I try to send params like a form with jest, but I recive always a error 500, this is my login.test.js

const request = require('supertest');
const app = require('../routes/login');

describe('Login', () => {
    test('Login correcto', async () => {
        const response = await request(app)
            .post('/login')
            .send({ user: 'hector' })
            .set('user', 'hector')
            .set('Content-Type', 'application/json')
        expect(response.statusCode).toEqual(200)
    });
});

this is my login.js from routes

 app.post('/login', (req, res) => {
    let body = req.body;
    let user = body.user;
    console.log(user);
    
    return res.status(200).send('okey');
});

I send the user like a form but it doesn't work, I receive an error 500, so what can I do?


Solution

  • The issue is that your Express app can't parse the JSON being sent to it. Adding the express.json middleware with app.use(express.json()); fixes your problem:

    const express = require('express');
    
    const app = express();
    
    app.use(express.json());
    
    app.post('/login', (req, res) => {
        let body = req.body;
        let user = body.user;
        console.log(user);
        
        return res.status(200).send('okey');
    });