use-detach-state.spec.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { FC } from 'react'
  2. import useDetachState from '../../../../frontend/js/shared/hooks/use-detach-state'
  3. import { EditorProviders } from '../../helpers/editor-providers'
  4. import { detachChannel, testDetachChannel } from '../../helpers/detach-channel'
  5. const DetachStateTest: FC<{
  6. stateKey: string
  7. defaultValue: any
  8. senderRole?: string
  9. targetRole?: string
  10. handleClick: (setValue: (value: any) => void) => void
  11. }> = ({ stateKey, defaultValue, handleClick, senderRole, targetRole }) => {
  12. const [value, setValue] = useDetachState(
  13. stateKey,
  14. defaultValue,
  15. senderRole,
  16. targetRole
  17. )
  18. return (
  19. <div>
  20. <div id="value">{value}</div>
  21. <button id="setValue" onClick={() => handleClick(setValue)}>
  22. set value
  23. </button>
  24. </div>
  25. )
  26. }
  27. describe('useDetachState', function () {
  28. it('create and update state', function () {
  29. cy.mount(
  30. <EditorProviders>
  31. <DetachStateTest
  32. stateKey="some-key"
  33. defaultValue="foobar"
  34. handleClick={setValue => {
  35. setValue('barbaz')
  36. }}
  37. />
  38. </EditorProviders>
  39. )
  40. cy.get('#value').should('have.text', 'foobar')
  41. cy.get('#setValue').click()
  42. cy.get('#value').should('have.text', 'barbaz')
  43. })
  44. it('broadcast message as sender', function () {
  45. window.metaAttributesCache.set('ol-detachRole', 'detacher')
  46. cy.mount(
  47. <EditorProviders>
  48. <DetachStateTest
  49. stateKey="some-key"
  50. defaultValue={null}
  51. senderRole="detacher"
  52. targetRole="detached"
  53. handleClick={setValue => {
  54. setValue('barbaz1')
  55. }}
  56. />
  57. </EditorProviders>
  58. )
  59. cy.spy(detachChannel, 'postMessage').as('postDetachMessage')
  60. cy.get('#setValue').click()
  61. cy.get('@postDetachMessage').should('have.been.calledWith', {
  62. role: 'detacher',
  63. event: 'state-some-key',
  64. data: { value: 'barbaz1' },
  65. })
  66. })
  67. it('receive message as target', function () {
  68. window.metaAttributesCache.set('ol-detachRole', 'detached')
  69. cy.mount(
  70. <EditorProviders>
  71. <DetachStateTest
  72. stateKey="some-key"
  73. defaultValue={null}
  74. senderRole="detacher"
  75. targetRole="detached"
  76. handleClick={() => {}}
  77. />
  78. </EditorProviders>
  79. )
  80. cy.wrap(null).then(() => {
  81. testDetachChannel.postMessage({
  82. role: 'detached',
  83. event: 'state-some-key',
  84. data: { value: 'barbaz2' },
  85. })
  86. })
  87. cy.get('#value').should('have.text', 'barbaz2')
  88. })
  89. })