'Jest POST test fails but works in Postman

I'm quite new to Node.js and started working on a simple project to apply what I learned so far. Wanted to start the project from the beginning with TDD in mind. Sadly I came across a problem that I can't figure out..

I've implemented user registration and a test for it but for some reason Jest is taking quite a long time executing it, usually resulting in a timeout. I changed it to 30 s but then another problem occurred, the status code returned is always 500 instead of the expected 201.

I tried it with Postman and everything works, user is created in the database, status code is 201 and it takes under 200 ms to execute.

Here is the code of the register function:

app.post('/api/users/register', async (req, res) => {
  try {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);
    const newUser = new User({ ...req.body, password: hashedPassword });
    const user = await newUser.save();

    res.status(201).json({ message: 'User created successfully.', user });
  } catch (error) {
    res.status(500).json(error);
  }
});

and the test:

const request = require('supertest');

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

jest.setTimeout(30000);

describe('User tests', () => {
  it('POST /api/users/register should create a new user', async () => {
    const response = await request(app)
      .post('/api/users/register')
      .send({
        username: 'test',
        email: '[email protected]',
        password: 'test123',
      })
      .expect('Content-Type', /json/)
      .expect(201);

    expect(response.body).toEqual(
      expect.objectContaining({
        message: 'User created successfully.',
        user: expect.objectContaining({
          username: 'test',
          email: '[email protected]',
          profilePic: '',
          role: 'User',
          password: expect.not.toBe('test123'),
        }),
      })
    );
  });
});

profilePic and role have default values in the model and this also works in Postman.

The complete code is on GitHub.

Thank you in advance for helping me figure it out.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source