helper.test.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展单元测试
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/10/24
  7. * @version
  8. */
  9. const { app, assert } = require('egg-mock/bootstrap');
  10. describe('test/app/extend/helper.test.js', () => {
  11. it('validateConvert test', function* () {
  12. // 创建 ctx
  13. const ctx = app.mockContext();
  14. const rule = {
  15. username: { type: 'string', required: true, allowEmpty: false, min: 4, max: 10 },
  16. group_id: { type: 'integer', required: true, allowEmpty: false, min: 4, max: 10 },
  17. password: { type: 'password', required: true, allowEmpty: false, min: 4 },
  18. confirm_password: { type: 'password', required: true, allowEmpty: false, min: 4, compare: 'password' },
  19. ip: 'isIP',
  20. telephone: 'isMobile',
  21. };
  22. // 转换为json验证
  23. let convertRule = ctx.helper.validateConvert(rule);
  24. convertRule = JSON.stringify(convertRule);
  25. let expectRule = {
  26. username: { required: true, minlength: 4, maxlength: 10 },
  27. group_id: { required: true, min: 4, max: 10 },
  28. password: { required: true, minlength: 4 },
  29. confirm_password: { required: true, minlength: 4, equalTo: '#password' },
  30. ip: 'isIP',
  31. telephone: 'isMobile',
  32. };
  33. expectRule = JSON.stringify(expectRule);
  34. assert(convertRule === expectRule);
  35. });
  36. it('generateRandomString test', function* () {
  37. // 创建 ctx
  38. const ctx = app.mockContext();
  39. const randomMix = ctx.helper.generateRandomString(4);
  40. const mixReg = /[A-Za-z0-9]{4}/;
  41. assert(mixReg.test(randomMix));
  42. // 测试纯数字
  43. const randomNumber = ctx.helper.generateRandomString(4, 2);
  44. const numberReg = /\d{4}/;
  45. assert(numberReg.test(randomNumber));
  46. // 测试纯字母
  47. const randomString = ctx.helper.generateRandomString(4, 3);
  48. const stringReg = /[A-Za-z]{4}/;
  49. assert(stringReg.test(randomString));
  50. });
  51. it('showSortFlag test', function* () {
  52. // 创建 ctx
  53. const ctx = app.mockContext({
  54. // sort: { test: 1 },
  55. sort: ['id', 'asc'],
  56. });
  57. const flag = ctx.helper.showSortFlag('id');
  58. assert(flag === '-');
  59. });
  60. it('isAjax test', function* () {
  61. // 创建 ctx
  62. const ctx = app.mockContext();
  63. const result = ctx.helper.isAjax(ctx);
  64. assert(!result);
  65. });
  66. it('sendRequest test', function* () {
  67. // 创建 ctx
  68. const ctx = app.mockContext();
  69. const url = 'http://ip.taobao.com/service/getIpInfo.php';
  70. const responseData = yield ctx.helper.sendRequest(url, { ip: '116.7.222.12' }, 'GET');
  71. assert(responseData.data.ip === '116.7.222.12');
  72. });
  73. });