config.test.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Tests for cfc-frontend config.js
  3. *
  4. * Tests environment detection logic by mocking uni.getAccountInfoSync.
  5. */
  6. import config from '@/config'
  7. beforeEach(() => {
  8. global.uni._storage = {}
  9. global.uni.getAccountInfoSync.mockReset()
  10. global.uni.getAccountInfoSync.mockReturnValue({
  11. miniProgram: { envVersion: 'develop' }
  12. })
  13. })
  14. // 与 config.js 保持一致:develop / trial / release 三端统一指向同一生产域名;
  15. // 非小程序环境、env 缺失或未知 envVersion 时,回落到模块顶部的默认值。
  16. // 换域名时只需改这两行(对应 config.js 的 switch 分支与顶部默认值)。
  17. const PROD_HOST = 'https://cfc.etotem.com.cn'
  18. const FALLBACK_HOST = 'http://cfc.iwintrue.com'
  19. describe('config.js', () => {
  20. beforeEach(() => {
  21. // Reset the module registry so each test gets a fresh config
  22. // (config.js 在模块加载时就求值 API_BASE_URL,必须重新 require 才会重跑这段逻辑)
  23. jest.resetModules()
  24. })
  25. test('uses production host when getAccountInfoSync returns develop', () => {
  26. global.uni.getAccountInfoSync.mockReturnValue({
  27. miniProgram: { envVersion: 'develop' }
  28. })
  29. const cfg = require('@/config').default
  30. expect(cfg.API_BASE_URL).toBe(PROD_HOST)
  31. })
  32. test('uses production host when envVersion is trial', () => {
  33. global.uni.getAccountInfoSync.mockReturnValue({
  34. miniProgram: { envVersion: 'trial' }
  35. })
  36. const cfg = require('@/config').default
  37. expect(cfg.API_BASE_URL).toBe(PROD_HOST)
  38. })
  39. test('uses production host when envVersion is release', () => {
  40. global.uni.getAccountInfoSync.mockReturnValue({
  41. miniProgram: { envVersion: 'release' }
  42. })
  43. const cfg = require('@/config').default
  44. expect(cfg.API_BASE_URL).toBe(PROD_HOST)
  45. })
  46. test('uses defaults when getAccountInfoSync throws', () => {
  47. global.uni.getAccountInfoSync.mockImplementation(() => {
  48. throw new Error('not in mini-program')
  49. })
  50. const cfg = require('@/config').default
  51. expect(cfg.API_BASE_URL).toBe(FALLBACK_HOST)
  52. })
  53. test('uses defaults for unknown envVersion', () => {
  54. global.uni.getAccountInfoSync.mockReturnValue({
  55. miniProgram: { envVersion: 'unknown' }
  56. })
  57. const cfg = require('@/config').default
  58. // Falls through the switch without matching, keeps defaults
  59. expect(cfg.API_BASE_URL).toBe(FALLBACK_HOST)
  60. })
  61. test('api(path) returns full URL joining API_BASE_URL + path', () => {
  62. const cfg = require('@/config').default
  63. const result = cfg.api('/api/test')
  64. expect(result).toBe(cfg.API_BASE_URL + '/api/test')
  65. })
  66. })