【问题标题】:Write a test in jest for adding a property to the response header开玩笑地写一个测试来为响应头添加一个属性
【发布时间】:2019-09-18 12:16:23
【问题描述】:

当用户登录时,我正在设置身份验证服务器; express 应该在响应标头中添加一个属性('x-auth-token'),路由实际工作,但我不知道如何为它写一个测试。

这是我的路由处理程序;

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:

【问题讨论】:

    标签: node.js mongodb express jestjs supertest


    【解决方案1】:

    这是您可以用来提供带有/不带有令牌的发布请求的功能。您必须在服务器变量中声明您部署的数据库 ip/地址

     /**
         * Post request function.
         * @param {String} endpoint - Endpoint to give post request.
         * @param {String} token - Token to validate-optional.
         * @param {Object} schema - Data to post.
         * @return {} Returns body response and status code.
         */
        async postRequest(endpoint, schema, token = 0) {
            if (token === 0) { return await request(server).post(endpoint).send(schema) }
            else { return await request(server).post(endpoint).set('x-auth-token', token).send(schema) };
        }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2019-11-10
      • 2019-07-23
      • 2021-06-16
      • 2018-09-25
      • 2018-10-23
      • 2018-11-24
      • 2022-10-06
      相关资源
      最近更新 更多