use-detach-state.test.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { act } from '@testing-library/react-hooks'
  2. import { expect } from 'chai'
  3. import { renderHookWithEditorContext } from '../../helpers/render-with-context'
  4. import sysendTestHelper from '../../helpers/sysend'
  5. import useDetachState from '../../../../frontend/js/shared/hooks/use-detach-state'
  6. const stateKey = 'some-key'
  7. describe('useDetachState', function () {
  8. beforeEach(function () {
  9. window.metaAttributesCache = new Map()
  10. })
  11. afterEach(function () {
  12. window.metaAttributesCache = new Map()
  13. })
  14. it('create and update state', async function () {
  15. const defaultValue = 'foobar'
  16. const { result } = renderHookWithEditorContext(() =>
  17. useDetachState(stateKey, defaultValue)
  18. )
  19. const [value, setValue] = result.current
  20. expect(value).to.equal(defaultValue)
  21. expect(setValue).to.be.a('function')
  22. const newValue = 'barbaz'
  23. act(() => {
  24. setValue(newValue)
  25. })
  26. expect(result.current[0]).to.equal(newValue)
  27. })
  28. it('broadcast message as sender', async function () {
  29. window.metaAttributesCache.set('ol-detachRole', 'detacher')
  30. const { result } = renderHookWithEditorContext(() =>
  31. useDetachState(stateKey, null, 'detacher', 'detached')
  32. )
  33. const [, setValue] = result.current
  34. sysendTestHelper.resetHistory()
  35. const newValue = 'barbaz'
  36. act(() => {
  37. setValue(newValue)
  38. })
  39. expect(sysendTestHelper.getLastBroacastMessage()).to.deep.equal({
  40. role: 'detacher',
  41. event: `state-${stateKey}`,
  42. data: { value: newValue },
  43. })
  44. })
  45. it('receive message as target', async function () {
  46. window.metaAttributesCache.set('ol-detachRole', 'detached')
  47. const { result } = renderHookWithEditorContext(() =>
  48. useDetachState(stateKey, null, 'detacher', 'detached')
  49. )
  50. const newValue = 'barbaz'
  51. sysendTestHelper.receiveMessage({
  52. role: 'detached',
  53. event: `state-${stateKey}`,
  54. data: { value: newValue },
  55. })
  56. expect(result.current[0]).to.equal(newValue)
  57. })
  58. })