test-wechat-official-account-open.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import assert from 'node:assert/strict'
  2. import { readFileSync } from 'node:fs'
  3. import test from 'node:test'
  4. function opener(wx) {
  5. const source = readFileSync(new URL('../utils/wechatOfficialAccount.js', import.meta.url), 'utf8')
  6. .replace(/^export /gm, '')
  7. return new Function('wx', `${source}; return openWechatOfficialAccount`)(wx)
  8. }
  9. test('profile API runs synchronously with original ID, never AppID', () => {
  10. const calls = [], events = []
  11. const open = opener({ openOfficialAccountProfile(options) { calls.push(options) } })
  12. open({ onUnavailable: () => events.push('fallback'), onComplete: () => events.push('complete') })
  13. assert.equal(calls.length, 1)
  14. assert.equal(calls[0].username, 'gh_53e43e6f5c92')
  15. calls[0].success({ errMsg: 'openOfficialAccountProfile:ok' })
  16. assert.deepEqual(events, ['complete'])
  17. })
  18. for (const runtime of [undefined, {}, { openOfficialAccountProfile: null }]) {
  19. test(`unsupported runtime falls back without crashing: ${JSON.stringify(runtime)}`, () => {
  20. const events = []
  21. opener(runtime)({ onUnavailable: () => events.push('fallback'), onComplete: () => events.push('complete') })
  22. assert.deepEqual(events, ['fallback', 'complete'])
  23. })
  24. }
  25. test('API failure provides fallback once even with repeated callbacks', () => {
  26. const events = []
  27. let options
  28. opener({ openOfficialAccountProfile(value) { options = value } })({
  29. onUnavailable: () => events.push('fallback'), onComplete: () => events.push('complete')
  30. })
  31. options.fail({ errMsg: 'fail: no permission' })
  32. options.fail({ errMsg: 'fail' })
  33. options.success({})
  34. assert.deepEqual(events, ['fallback', 'complete'])
  35. })
  36. test('synchronous native exception releases busy state and falls back', () => {
  37. const events = []
  38. opener({ openOfficialAccountProfile() { throw new Error('unsupported') } })({
  39. onUnavailable: () => events.push('fallback'), onComplete: () => events.push('complete')
  40. })
  41. assert.deepEqual(events, ['fallback', 'complete'])
  42. })