Test error - Chai/Mocha

Asked

Viewed 68 times

1

Hello! I’m studying unit trials with Chai and Mocha. I’ve never touched it before, but now I’m feeling the need to learn about it. I have the following code:

module.exports = {
//Create - Method POST
async storeNewUser(request, response) {
    const { name, email, password } = request.body;
    const passwordEncripted = await bcrypt.hash(password, 10);

    const user = await User.findOrCreate({
        where: {
            email
        }, 
        defaults: { name, password: passwordEncripted }
    }).spread((userResult, created) => {
        if (created) {
            const token = generateNewToken(userResult.id);
            userResult.password = undefined;
            return response.status(201).json({ userResult, token });
        }
        return response.status(400).json({message: "User already exists."});
    });
},

I created the following test for the storeNewUser function()

const chai = require('chai');
const http = require('chai-http');
const subset = require('chai-subset');

const User = require('../src/app/controllers/User');

chai.use(http);
chai.use(subset);

const userSchema = {
    userResult: {
        name: name => name,
        email: email => email,
        password: password => password
    },
    token: {
        token: token => token
    }
};

describe('Integration test', () => {
    it ('/users - POST', () => {
        chai.request(User.storeNewUser).post('/users').send({
            name: "Nome do Usuario",
            email: "[email protected]",
            password: "54321"
        }).end((err, res) => {
            chai.expect(err).to.be.null;
            chai.expect(res).to.have.status(201);
            chai.expect(res.body).to.containSubset([userSchema]);
        });
    });
});

When I run the test the following error appears:

inserir a descrição da imagem aqui

This is my index.js file where I create the application and call the app.use(express.json())

const express = require('express');
const app = express();
const cors = require('cors');
const PORT = 3000;

require('./database');

app.use(express.json());
app.use(cors());

app.use(require('./routes'));

// These routes require authentication
app.use(require('./auth-routes'));

app.listen(PORT, console.log('Server running on port '+ PORT));

This is my archive of Routes.js routes

const express = require('express');
const router = express.Router();

const userController = require('./app/controllers/User');
const authController = require('./app/controllers/Auth');

router.post('/login', authController.login);
router.post('/users', userController.storeNewUser);

module.exports = router;

Does anyone have any idea where I’m going wrong?

  • Put pf code and not code images... I do not see request.body nowhere. Are you sure you’re showing the right code?

  • request.body is on line 4 of the first block of code. I did a breakdown.

  • That one chai.request(User.storeNewUser) implements the body in the request? On Node you have the body-parser that does this in Express for example... this may be the problem, that it is creating a different mock than you have in the application.

  • I have a Routes.js file that calls function I’m wanting to test.

  • router.post('/users', userController.storeNewUser);

  • Yeah, I get that, and at the Express you’re using the body-parser or app.use(express.json())?

  • 1

    app.use(express.json());

  • Behold this part of the chai-http (in the npm). When to use the .end(), becomes necessary to receive the function done (as a parameter of callback of it()), to be able to signal when the test has actually been completed.

Show 3 more comments

1 answer

1

I found the problem!

I was calling the function I want to test when I wrote:

chai.request(User.storeNewUser).post('/users').send({

The correct thing is I call the application as now:

const app = require('../src/index');

chai.request(app).post('/users').send({

Thanks Sergio and Gustavo Sampaio for their help.

Browser other questions tagged

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