invokeFunction.test.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import tcb from '../../src/index'
  2. import assert from 'assert'
  3. import config from '../config.local'
  4. import { ERROR } from '../../lib/const/code'
  5. describe('functions.invokeFunction: 执行云函数', () => {
  6. const app = tcb.init(config)
  7. it('校验调用云函数传参', async () => {
  8. let a: any = {}
  9. let b: any = {}
  10. a.c = b
  11. b.c = a
  12. let result
  13. try {
  14. result = await app.callFunction({
  15. name: 'test',
  16. data: a
  17. })
  18. } catch (e) {
  19. assert(e.code === ERROR.INVALID_PARAM.code && e.message === '对象出现了循环引用')
  20. }
  21. try {
  22. result = await app.callFunction({
  23. name: '',
  24. data: { a: 1 }
  25. })
  26. } catch (e) {
  27. assert(e.code === ERROR.INVALID_PARAM.code && e.message === '函数名不能为空')
  28. }
  29. })
  30. it('执行不存在的云函数', async () => {
  31. expect.assertions(1)
  32. try {
  33. const result = await app.callFunction({
  34. name: 'unexistFunction',
  35. data: { a: 1 }
  36. })
  37. } catch (e) {
  38. expect(e.code).toBe('FUNCTION_NOT_FOUND')
  39. }
  40. })
  41. // 灰度期间暂不放开新特性
  42. it('执行云函数 设定自定义超时', async () => {
  43. try {
  44. const result = await app.callFunction(
  45. {
  46. name: 'test',
  47. data: { a: 1 }
  48. },
  49. {
  50. timeout: 10
  51. }
  52. )
  53. assert(!result)
  54. } catch (err) {
  55. assert(err.code === 'ESOCKETTIMEDOUT')
  56. }
  57. }, 30000)
  58. it('mock callFunction 回包为string', async () => {
  59. jest.resetModules()
  60. jest.mock('request', () => {
  61. return jest.fn().mockImplementation((params, callback) => {
  62. const body = { data: { response_data: 'test' } }
  63. process.nextTick(() => {
  64. callback(null, { statusCode: 200, body })
  65. })
  66. })
  67. })
  68. const tcb1 = require('../../src/index')
  69. const app1 = tcb1.init(config)
  70. try {
  71. let result = await app1.callFunction({
  72. name: 'unexistFunction',
  73. data: { a: 1 }
  74. })
  75. // console.log(result)
  76. assert(typeof result.result === 'string')
  77. } catch (err) {
  78. console.log(err)
  79. }
  80. })
  81. it.only('function debug', async () => {
  82. const app = tcb.init(config)
  83. const callRes = await app.callFunction({
  84. name: 'invoke',
  85. data: {
  86. key1: 'test value 1',
  87. key2: 'test value 2',
  88. userInfo: {
  89. // appId: '',
  90. openId: 'oaoLb4qz0R8STBj6ipGlHkfNCO2Q'
  91. }
  92. }
  93. })
  94. console.log('callRes:', callRes)
  95. })
  96. })