mardi 29 décembre 2020

How to test router post in jest?

I would like to test this

router.route('/').post(isValid, registerUser).get(protect);

So I create user.test.js with

const userData = {
  email: faker.internet.email(),
  firstname: 'Kiki',
  lastname: 'bibi',
  age: faker.random.number(),
  password:faker.internet.password(),
};

describe('insert', () => {
  beforeAll(async () => {
    dotenv.config();

    connectDB();
  });
});
describe("POST / register", () => {
it("Should create new user", async () => {
    const validUser = new User(userData);
    const savedUser = await validUser.save();
    const res = await router.route('/').post(isValid, registerUser).get(protect);
    expect(savedUser._id).toBeDefined();
    expect(savedUser.email).toBe(userData.email);
    expect(savedUser.firstname).toBe(userData.firstname);
    expect(savedUser.lastname).toBe(userData.lastname);
    expect(savedUser.age).toBe(userData.age);
});
});
afterAll(async (done) => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close();
  done();
});

But it's not working, it's only connect to the db I would like to try test with isValid because it's test users

  check('email', 'Please include a valid email').isEmail(),
  check('password', 'Password is required')
    .exists()
    .isLength({ min: 8, max: 40 }),
  check('firstname', 'Fisrtname is required').exists().notEmpty(),
  check('lastname', 'Lastname is required').exists().notEmpty(),
  check('age', 'Age must be 13 or more').exists().isInt({ min: 13 }),
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty())
      return res.status(422).json({ errors: errors.array() });
    next();
  },
];

Anyone can explain me how to test with jest ? Many thanks

Aucun commentaire:

Enregistrer un commentaire