node.js - 如何正确地对 Joi Schemas 验证进行单元测试?

标签 node.js unit-testing jestjs supertest joi

我创建了一个在我的路由中调用的 Joi 验证模式。但是,当我运行代码覆盖率时,该文件没有被覆盖。所以,我正在尝试为它编写一个测试。
验证器.js

    const Joi = require('joi');
    module.exports = {
    validateExternalId: (schema, name) => {
    return (req, res, next) => {
      const result = Joi.validate({ param: req.params[name] }, schema);
      if (result.error) {
        return res.status(400).send(result.error.details[0].message);
      }
      next();
    };
  },
schemas: {
    idSchema: Joi.object().keys({
      param: Joi.string().regex(/^[a-zA-Z0-9]{20}$/).required()
    })
  }
};
验证器.test.js
const { validateExternalId, schemas } = require('../../src/helpers/validation');
const app = require('../../src/router')

const mockResponse = () => {
  const res = {};
  res.status = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
};

describe('Testing validateExternalId schema', () => {
  it('It can validate the external Id Regex length', done => {
    const req = {
      params: [
        {
          extClientId: 'abcdefghij0123456789'
        }
      ]
    };

  app.use('/token/:extClientId', validateExternalId(schemas.idSchema, 'extClientId');
    // expect().toHaveBeenCalled();
  });
});
请放轻松……这是我测试这个 Joi 验证器的尝试。我尝试过,但我的预期不起作用,所以我现在将其注释掉。任何指针将不胜感激。谢谢你

最佳答案

这是单元测试解决方案:
validator.js :

const Joi = require('joi');

module.exports = {
  validateExternalId: (schema, name) => {
    return (req, res, next) => {
      const result = Joi.validate({ param: req.params[name] }, schema);
      if (result.error) {
        return res.status(400).send(result.error.details[0].message);
      }
      next();
    };
  },
  schemas: {
    idSchema: Joi.object().keys({
      param: Joi.string()
        .regex(/^[a-zA-Z0-9]{20}$/)
        .required(),
    }),
  },
};
validator.test.js :

const { validateExternalId, schemas } = require('./validator');
const Joi = require('joi');

describe('60730701', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should send error', () => {
    const validationResults = { error: { details: [{ message: 'validation error' }] } };
    const validateSpy = jest.spyOn(Joi, 'validate').mockReturnValueOnce(validationResults);
    const mReq = { params: { extClientId: '123' } };
    const mRes = { status: jest.fn().mockReturnThis(), send: jest.fn() };
    validateExternalId(schemas.idSchema, 'extClientId')(mReq, mRes);
    expect(validateSpy).toBeCalledWith({ param: '123' }, schemas.idSchema);
    expect(mRes.status).toBeCalledWith(400);
    expect(mRes.send).toBeCalledWith('validation error');
  });

  it('should pass the validation and call api', () => {
    const validationResults = { error: undefined };
    const validateSpy = jest.spyOn(Joi, 'validate').mockReturnValueOnce(validationResults);
    const mReq = { params: { extClientId: '123' } };
    const mRes = {};
    const mNext = jest.fn();
    validateExternalId(schemas.idSchema, 'extClientId')(mReq, mRes, mNext);
    expect(validateSpy).toBeCalledWith({ param: '123' }, schemas.idSchema);
    expect(mNext).toBeCalled();
  });
});

100% 覆盖率的单元测试结果:

 PASS  stackoverflow/60730701/validator.test.js (9.96s)
  60730701
    ✓ should send error (6ms)
    ✓ should pass the validation and call api (2ms)

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |     100 |      100 |     100 |     100 |                   
 validator.js |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.647s, estimated 15s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60730701

关于node.js - 如何正确地对 Joi Schemas 验证进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60730701/

相关文章:

node.js - 如何使用 fluent-ffmpeg 从图像缓冲区创建视频?

node.js - 如何使用无服务器模块在本地调试 AWS Lambda Node.js?

reactjs - 方法 “simulate” 旨在在 1 个节点上运行。 0 找到了。 - Jest/ enzyme

python - 修补猎鹰 Hook

json - 如何断言两个 JSON 字符串表示的数据相等?

javascript - Jest 模拟导航服务

javascript - jest.mock 不适用于 Javascript 测试和 Typescript 模块

node.js - 如何在 "real world"时间内每 n 毫秒调用一个函数?

node.js - Node Http 代理 Web 套接字平衡

unit-testing - 在 Elixir 应用程序中使用 espec 测试异常