helper.test.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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('generateRandomString test', function* () {
  12. // 创建 ctx
  13. const ctx = app.mockContext();
  14. const randomMix = ctx.helper.generateRandomString(4);
  15. const mixReg = /[A-Za-z0-9]{4}/;
  16. assert(mixReg.test(randomMix));
  17. // 测试纯数字
  18. const randomNumber = ctx.helper.generateRandomString(4, 2);
  19. const numberReg = /\d{4}/;
  20. assert(numberReg.test(randomNumber));
  21. // 测试纯字母
  22. const randomString = ctx.helper.generateRandomString(4, 3);
  23. const stringReg = /[A-Za-z]{4}/;
  24. assert(stringReg.test(randomString));
  25. });
  26. it('showSortFlag test', function* () {
  27. // 创建 ctx
  28. const ctx = app.mockContext({
  29. // sort: { test: 1 },
  30. sort: ['id', 'asc'],
  31. });
  32. const flag = ctx.helper.showSortFlag('id');
  33. assert(flag === '-');
  34. });
  35. it('isAjax test', function* () {
  36. // 创建 ctx
  37. const ctx = app.mockContext();
  38. const result = ctx.helper.isAjax(ctx);
  39. assert(!result);
  40. });
  41. it('sendRequest test', function* () {
  42. // 创建 ctx
  43. const ctx = app.mockContext();
  44. const url = 'http://ip.taobao.com/service/getIpInfo.php';
  45. const responseData = yield ctx.helper.sendRequest(url, { ip: '116.7.222.12' }, 'GET');
  46. assert(responseData.data.ip === '116.7.222.12');
  47. });
  48. it('explode paths', function* () {
  49. // 创建 ctx
  50. const ctx = app.mockContext();
  51. const paths = ['1.2.3.4.5', '1.2.3.5.7'];
  52. const normal = ctx.helper.explodePath(paths, '.');
  53. const normalExpect = ['1', '1.2', '1.2.3', '1.2.3.4', '1.2.3.4.5', '1.2.3.5', '1.2.3.5.7'];
  54. let result = true;
  55. try {
  56. for (const index in normal) {
  57. if (normal[index] !== normalExpect[index]) {
  58. throw '数据错误';
  59. }
  60. }
  61. } catch (error) {
  62. result = false;
  63. }
  64. assert(result);
  65. });
  66. it('test permission', function* () {
  67. // 创建 ctx
  68. const ctx = app.mockContext();
  69. ctx.session = {
  70. sessionUser: {
  71. permission: '1,2,3,4',
  72. },
  73. };
  74. const permission = require('../../../config/permission');
  75. let result = ctx.helper.hasPermission(permission.permission.VIEW_STAGE_MEASURE);
  76. assert(!result);
  77. // 多个权限判断
  78. result = ctx.helper.hasPermission([permission.permission.CREATE_TENDER, permission.permission.VIEW_ALL_TENDER]);
  79. assert(result);
  80. });
  81. });