render-with-subscription-dash-context.tsx 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { render } from '@testing-library/react'
  2. import _ from 'lodash'
  3. import { SubscriptionDashboardProvider } from '../../../../../frontend/js/features/subscription/context/subscription-dashboard-context'
  4. import { groupPriceByUsageTypeAndSize, plans } from '../fixtures/plans'
  5. import fetchMock from 'fetch-mock'
  6. export function renderWithSubscriptionDashContext(
  7. component: React.ReactElement,
  8. options?: {
  9. metaTags?: {
  10. name: string
  11. value: string | object | Array<object> | boolean
  12. }[]
  13. recurlyNotLoaded?: boolean
  14. queryingRecurly?: boolean
  15. currencyCode?: string
  16. }
  17. ) {
  18. const SubscriptionDashboardProviderWrapper = ({
  19. children,
  20. }: {
  21. children: React.ReactNode
  22. }) => (
  23. <SubscriptionDashboardProvider>{children}</SubscriptionDashboardProvider>
  24. )
  25. window.metaAttributesCache = new Map()
  26. options?.metaTags?.forEach(tag =>
  27. window.metaAttributesCache.set(tag.name, tag.value)
  28. )
  29. if (!options?.recurlyNotLoaded) {
  30. // @ts-ignore
  31. global.recurly = {
  32. configure: () => {},
  33. Pricing: {
  34. Subscription: () => {
  35. return {
  36. plan: (planCode: string) => {
  37. let plan
  38. const isGroupPlan = planCode.includes('group')
  39. if (isGroupPlan) {
  40. const [, planType, size, usage] = planCode.split('_')
  41. const currencyCode = options?.currencyCode || 'USD'
  42. plan = _.get(groupPriceByUsageTypeAndSize, [
  43. usage,
  44. planType,
  45. currencyCode,
  46. size,
  47. ])
  48. } else {
  49. plan = plans.find(p => p.planCode === planCode)
  50. }
  51. const response = {
  52. next: {
  53. total: plan?.price_in_cents
  54. ? plan.price_in_cents / 100
  55. : undefined,
  56. },
  57. }
  58. return {
  59. currency: () => {
  60. return {
  61. catch: () => {
  62. return {
  63. done: (callback: (response: object) => void) => {
  64. if (!options?.queryingRecurly) {
  65. return callback(response)
  66. }
  67. },
  68. }
  69. },
  70. }
  71. },
  72. }
  73. },
  74. }
  75. },
  76. },
  77. }
  78. }
  79. return render(component, {
  80. wrapper: SubscriptionDashboardProviderWrapper,
  81. })
  82. }
  83. export function cleanUpContext() {
  84. // @ts-ignore
  85. delete global.recurly
  86. window.metaAttributesCache = new Map()
  87. fetchMock.reset()
  88. }