Typeerror: Cannot destructure Property `name` of 'Undefined' or 'null'

Asked

Viewed 765 times

1

I’m using jest along with supertest to test my application endpoints. The tests with the get requests are working, but the test with the post request is giving error:

inserir a descrição da imagem aqui

clientRoutes.test.js

const supertest = require('supertest')
const clientRoutes = require('../Routes/clientRoutes');
const db = require('../database_connection');

describe('Test the clients path', () => {
test('should post client', async () => {

        const { rows } = await db.query("SELECT * FROM client WHERE name = 'baz'")
        console.log(rows[0]);
        const res = await supertest(clientRoutes)
            .post('/client')
            .send({ name: 'baz', password: 333333 })
            .set('Accept', 'application/json')
        expect(res.body).toEqual(rows[0])
    });
})

clientRoutes.js

const express = require('express')
const clientController = require('../controllers/clientController');

const routes = express()

...
routes.post('/client', clientController.create)
...

module.exports = routes;

clientController.js

const db = require('../database_connection');
module.exports = {

    ...

    async create(req, res) {
        let { name, password } = req.body
        password += crypto.randomBytes(4).toString('HEX')

        const { rows } = await db.query('INSERT INTO carrinho_de_compras.client VALUES ($1, $2)')
        res.send(rows[0])
    }

   ...          
}
  • let { name, password } = JSON.parse(req.body);

  • worked out, thanks ^^

1 answer

3


You need in your file that you raise the FAKE API with supertest, put this. Because then your server is able to receive requests in JSON format. The format the colleague above put using JSON.parse(req.body) is correct too, but it is easier to do the way I put it, because otherwise every time you go to do a POST will need to put JSON.parse().

const routes = express();

routes.use(express.json());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.