Напишите тест в шутку для добавления свойства в заголовок ответа - PullRequest
0 голосов
/ 29 апреля 2019

Я настраиваю сервер аутентификации, когда пользователь вошел в систему; Экспресс должен добавить свойство ('x-auth-token') к заголовку ответа, маршрут фактически работает, но я не знаю, как написать тест для этого в jest.

вот мой обработчик маршрута;

const bcrypt = require('bcrypt');
const { User } = require('../models/user');
const Joi = require('joi');
const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {
  const { error } = validation(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const { email, password } = req.body;

  const user = await User.findOne({ email });

  if (!user || !(await bcrypt.compare(password, user.password)))
    return res.status(400).send('Invalid email or password.');

  // here express adding the token to header 

  res
    .header('x-auth-token', user.generateAuthToken())
    .send(JSON.stringify(`Welcome dear ${user.name}`));
});

function validation(value) {
  const schema = {
    email: Joi.string()
      .min(10)
      .max(255)
      .email()
      .required(),
    password: Joi.string()
      .min(8)
      .max(1024)
      .required()
  };

  return Joi.validate(value, schema);
}

module.exports = router;

вот мой тест:

пользователь доступен в MongoDB, адрес электронной почты и пароль действительны.

const request = require('supertest');

const execude = () => {
  return request(server)
    .post('/api/auth')
    .send({ email, password });
};

it('should place token in x-auth-token if request is valid', async () => {
  const res = await execude();

  expect(res.header).to.haveKey('x-auth-token');
});

шутка консоли

  ● /auth › POST/ › should place token in x-auth-token if request is valid

    expect(object).toHaveProperty(path)

    Expected the object:
      {"connection": "close", "content-length": "26", "content-type": "text/html; charset=utf-8", "date": "Mon, 29 Apr 2019 20:54:45 GMT", "etag": "W/\"1a-ARJvVK+smzAF3QQve2mDSG+3Eus\"", "strict-transport-security": "max-age=15552000; includeSubDomains", "x-content-type-options": "nosniff", "x-dns-prefetch-control": "off", "x-download-options": "noopen", "x-frame-options": "SAMEORIGIN", "x-xss-protection": "1; mode=block"}
    To have a nested property:
      "x-auth-token"

      94 |       const res = await execude();
      95 | 
    > 96 |       expect(res.header).toHaveProperty('x-auth-token');
         |                          ^
      97 |     });
      98 |     // should send specific string if request is valid
      99 |   });

      at Object.toHaveProperty (tests/integration/authentication.test.js:96:

...