js_validator.test.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. /**
  3. * jsvalidator单元测试
  4. *
  5. * @author CaiAoLin
  6. * @date 2018/2/7
  7. * @version
  8. */
  9. const JsValidator = require('../../../app/lib/js_validator');
  10. const { app, assert } = require('egg-mock/bootstrap');
  11. describe('test/app/lib/js_validator.test.js', () => {
  12. it('test convert', function* () {
  13. // 创建 ctx
  14. const ctx = app.mockContext();
  15. const jsValidator = new JsValidator(ctx);
  16. const rule = {
  17. username: { type: 'string', required: true, allowEmpty: false, min: 4, max: 10 },
  18. group_id: { type: 'integer', required: true, allowEmpty: false, min: 4, max: 10 },
  19. password: { type: 'password', required: true, allowEmpty: false, min: 4 },
  20. confirm_password: { type: 'password', required: true, allowEmpty: false, min: 4, compare: 'password' },
  21. ip: { type: 'ip', allowEmpty: false },
  22. telephone: { type: 'mobile', allowEmpty: false },
  23. };
  24. // 转换为json验证
  25. jsValidator.convert(rule);
  26. const convertRule = JSON.stringify(jsValidator.rule);
  27. let expectRule = {
  28. username: { required: true, minlength: 4, maxlength: 10 },
  29. group_id: { required: true, min: 4, max: 10 },
  30. password: { required: true, minlength: 4 },
  31. confirm_password: { required: true, minlength: 4, equalTo: '#password' },
  32. ip: { ip: true, required: true },
  33. telephone: { mobile: true, required: true },
  34. };
  35. expectRule = JSON.stringify(expectRule);
  36. assert(convertRule === expectRule);
  37. });
  38. it('test js validator', function* () {
  39. const ctx = app.mockContext();
  40. const jsValidator = new JsValidator(ctx);
  41. const rule = {
  42. username: { type: 'string', required: true, allowEmpty: false, min: 4, max: 10 },
  43. group_id: { type: 'integer', required: true, allowEmpty: false, min: 4, max: 10 },
  44. password: { type: 'password', required: true, allowEmpty: false, min: 4 },
  45. confirm_password: { type: 'password', required: true, allowEmpty: false, min: 4, compare: 'password' },
  46. ip: { type: 'ip', allowEmpty: false },
  47. telephone: { type: 'mobile', allowEmpty: false },
  48. };
  49. const jsCode = jsValidator.convert(rule).build();
  50. assert(jsCode !== '');
  51. });
  52. });