socket.spec.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import { act, fireEvent, render, RenderResult } from '@testing-library/react';
  2. import WS from 'jest-websocket-mock';
  3. import React, { Dispatch } from 'react';
  4. import * as storageHooks from 'react-storage-hooks';
  5. import { AnyAction, LocalAction, RemoteAction } from '../actions';
  6. import * as effects from '../effects/effects';
  7. import { GlobalState } from '../reducer';
  8. import { useOnMessage, useDispatchWithEffects, useSocket } from './socket';
  9. jest.mock('nanoid', () => ({
  10. nanoid: (): string => 'A5v3D',
  11. }));
  12. describe(useOnMessage.name, () => {
  13. const dispatch: Dispatch<AnyAction> = jest.fn();
  14. const testMessage = {
  15. data: JSON.stringify({
  16. type: 'SOME_ACTION_FROM_SOCKET',
  17. payload: {
  18. some: 'thing',
  19. },
  20. }),
  21. } as MessageEvent<unknown>;
  22. const TestComponent: React.FC = () => {
  23. const onMessage = useOnMessage(dispatch);
  24. return <button onClick={(): void => onMessage(testMessage)}>Simulate message!</button>;
  25. };
  26. it('should return a function which dispatches actions', () => {
  27. expect.assertions(2);
  28. const { getByText } = render(<TestComponent />);
  29. act(() => {
  30. fireEvent.click(getByText('Simulate message!'));
  31. });
  32. expect(dispatch).toHaveBeenCalledTimes(1);
  33. expect(dispatch).toHaveBeenCalledWith({
  34. type: 'SOME_ACTION_FROM_SOCKET',
  35. payload: {
  36. some: 'thing',
  37. },
  38. });
  39. });
  40. });
  41. describe(useDispatchWithEffects.name, () => {
  42. const someAction = ({
  43. type: 'SOME_ACTION',
  44. payload: 'yes',
  45. } as unknown) as LocalAction;
  46. const state = ({ my: 'state' } as unknown) as GlobalState;
  47. const dispatch: Dispatch<AnyAction> = jest.fn();
  48. const socket = ({
  49. send: jest.fn(),
  50. OPEN: WebSocket.OPEN,
  51. readyState: WebSocket.OPEN,
  52. } as unknown) as WebSocket;
  53. const someEffect = ({
  54. type: 'SOME_EFFECT',
  55. payload: {
  56. fromClient: 'us',
  57. data: 'yes',
  58. },
  59. } as unknown) as RemoteAction;
  60. const TestComponent: React.FC = () => {
  61. const dispatchWithEffects = useDispatchWithEffects(state, dispatch, socket);
  62. return (
  63. <>
  64. <button onClick={(): void => dispatchWithEffects(someAction)}>Dispatch!</button>
  65. </>
  66. );
  67. };
  68. describe('when an action is dispatched', () => {
  69. let globalEffectsSpy: jest.SpyInstance;
  70. describe('and no effect is associated', () => {
  71. beforeEach(() => {
  72. globalEffectsSpy = jest.spyOn(effects, 'globalEffects').mockReturnValueOnce(null);
  73. });
  74. it('should dispatch the action to the local store', () => {
  75. expect.assertions(2);
  76. const { getByText } = render(<TestComponent />);
  77. act(() => {
  78. fireEvent.click(getByText('Dispatch!'));
  79. });
  80. expect(dispatch).toHaveBeenCalledTimes(1);
  81. expect(dispatch).toHaveBeenCalledWith(someAction);
  82. });
  83. it('should not send a message to the socket', () => {
  84. expect.assertions(1);
  85. const { getByText } = render(<TestComponent />);
  86. act(() => {
  87. fireEvent.click(getByText('Dispatch!'));
  88. });
  89. expect(socket.send).not.toHaveBeenCalled();
  90. });
  91. });
  92. describe('and an effect is associated', () => {
  93. beforeEach(() => {
  94. globalEffectsSpy = jest.spyOn(effects, 'globalEffects').mockReturnValueOnce(someEffect);
  95. });
  96. it('should dispatch the action to the local store', () => {
  97. expect.assertions(2);
  98. const { getByText } = render(<TestComponent />);
  99. act(() => {
  100. fireEvent.click(getByText('Dispatch!'));
  101. });
  102. expect(dispatch).toHaveBeenCalledTimes(1);
  103. expect(dispatch).toHaveBeenCalledWith(someAction);
  104. });
  105. it('should send a message to the socket', () => {
  106. expect.assertions(4);
  107. const { getByText } = render(<TestComponent />);
  108. act(() => {
  109. fireEvent.click(getByText('Dispatch!'));
  110. });
  111. expect(globalEffectsSpy).toHaveBeenCalledTimes(1);
  112. expect(globalEffectsSpy).toHaveBeenCalledWith(state, someAction);
  113. expect(socket.send).toHaveBeenCalledTimes(1);
  114. expect(socket.send).toHaveBeenCalledWith(JSON.stringify(someEffect));
  115. });
  116. });
  117. });
  118. });
  119. describe(useSocket.name, () => {
  120. afterEach(WS.clean);
  121. const onMessage = jest.fn();
  122. const onLogin = jest.fn();
  123. const TestComponent: React.FC = () => {
  124. const { onIdentify, socket, ...hookResult } = useSocket(onMessage, onLogin);
  125. return (
  126. <>
  127. <button onClick={(): void => onIdentify('my-client-name')}>Identify!</button>
  128. <button onClick={(): void => socket?.send('Hello world!')}>Say hello!</button>
  129. <div data-testid="hook-result">{JSON.stringify(hookResult)}</div>
  130. </>
  131. );
  132. };
  133. it.each`
  134. testCase | key | expectedValue
  135. ${'the name'} | ${'name'} | ${''}
  136. ${'the error status'} | ${'error'} | ${false}
  137. ${'the connecting status'} | ${'connecting'} | ${false}
  138. ${'the connected status'} | ${'connected'} | ${false}
  139. `('should return $testCase', ({ key, expectedValue }) => {
  140. expect.assertions(1);
  141. const { getByTestId } = render(<TestComponent />);
  142. expect(JSON.parse(getByTestId('hook-result').innerHTML)).toStrictEqual(
  143. expect.objectContaining({
  144. [key]: expectedValue,
  145. }),
  146. );
  147. });
  148. describe('when identifying', () => {
  149. let server: WS;
  150. const saveName: React.Dispatch<unknown> = jest.fn();
  151. beforeEach(() => {
  152. server = new WS('ws://my-api.url:1234/pubsub');
  153. jest
  154. .spyOn(storageHooks, 'useStorageState')
  155. .mockReturnValue(['' as unknown, saveName, undefined]);
  156. });
  157. const setupIdentify = (): RenderResult => {
  158. const renderResult = render(<TestComponent />);
  159. act(() => {
  160. fireEvent.click(renderResult.getByText('Identify!'));
  161. });
  162. return renderResult;
  163. };
  164. it('should create a new connection to the socket, using a unique client name in the query', async () => {
  165. expect.assertions(1);
  166. setupIdentify();
  167. const res = await server.connected;
  168. expect(res.url).toBe('ws://my-api.url:1234/pubsub?client-name=my-client-name-A5v3D');
  169. });
  170. it('should open a new socket', async () => {
  171. expect.assertions(2);
  172. const { getByText } = setupIdentify();
  173. await act(async () => {
  174. await server.connected;
  175. });
  176. act(() => {
  177. fireEvent.click(getByText('Say hello!'));
  178. });
  179. await expect(server).toReceiveMessage('Hello world!');
  180. expect(server).toHaveReceivedMessages(['Hello world!']);
  181. });
  182. it('should set the connected state to true', async () => {
  183. expect.assertions(1);
  184. const { getByTestId } = setupIdentify();
  185. await act(async () => {
  186. await server.connected;
  187. });
  188. expect(JSON.parse(getByTestId('hook-result').innerHTML)).toStrictEqual(
  189. expect.objectContaining({
  190. connecting: false,
  191. connected: true,
  192. }),
  193. );
  194. });
  195. it('should return the unique name', async () => {
  196. expect.assertions(1);
  197. const { getByTestId } = setupIdentify();
  198. await act(async () => {
  199. await server.connected;
  200. });
  201. expect(JSON.parse(getByTestId('hook-result').innerHTML)).toStrictEqual(
  202. expect.objectContaining({
  203. name: 'my-client-name-A5v3D',
  204. }),
  205. );
  206. });
  207. it('should save the client name', async () => {
  208. expect.assertions(2);
  209. setupIdentify();
  210. await act(async () => {
  211. await server.connected;
  212. });
  213. expect(saveName).toHaveBeenCalledTimes(1);
  214. expect(saveName).toHaveBeenCalledWith('my-client-name');
  215. });
  216. it('should call onLogin', async () => {
  217. expect.assertions(2);
  218. setupIdentify();
  219. await act(async () => {
  220. await server.connected;
  221. });
  222. expect(onLogin).toHaveBeenCalledTimes(1);
  223. expect(onLogin).toHaveBeenCalledWith('my-client-name-A5v3D');
  224. });
  225. });
  226. describe('when the name is stored in localStorage', () => {
  227. let server: WS;
  228. const saveName: React.Dispatch<unknown> = jest.fn();
  229. beforeEach(() => {
  230. server = new WS('ws://my-api.url:1234/pubsub');
  231. jest
  232. .spyOn(storageHooks, 'useStorageState')
  233. .mockReturnValue(['my-stored-name' as unknown, saveName, undefined]);
  234. });
  235. it('should set connecting to true', () => {
  236. expect.assertions(1);
  237. const { getByTestId } = render(<TestComponent />);
  238. expect(JSON.parse(getByTestId('hook-result').innerHTML)).toStrictEqual(
  239. expect.objectContaining({
  240. connecting: true,
  241. connected: false,
  242. }),
  243. );
  244. });
  245. it('should open a socket immediately, using a unique version of the stored name', async () => {
  246. expect.assertions(3);
  247. const { getByText } = render(<TestComponent />);
  248. const res = await server.connected;
  249. expect(res.url).toBe('ws://my-api.url:1234/pubsub?client-name=my-stored-name-A5v3D');
  250. act(() => {
  251. fireEvent.click(getByText('Say hello!'));
  252. });
  253. await expect(server).toReceiveMessage('Hello world!');
  254. expect(server).toHaveReceivedMessages(['Hello world!']);
  255. });
  256. it('should set connecting to false after the socket is connected', async () => {
  257. expect.assertions(1);
  258. const { getByTestId } = render(<TestComponent />);
  259. await server.connected;
  260. expect(JSON.parse(getByTestId('hook-result').innerHTML)).toStrictEqual(
  261. expect.objectContaining({
  262. connecting: false,
  263. connected: true,
  264. }),
  265. );
  266. });
  267. });
  268. describe('when a message is received from the server', () => {
  269. let server: WS;
  270. beforeEach(() => {
  271. server = new WS('ws://my-api.url:1234/pubsub');
  272. });
  273. it('should call onMessage', async () => {
  274. expect.assertions(2);
  275. const { getByText } = render(<TestComponent />);
  276. act(() => {
  277. fireEvent.click(getByText('Identify!'));
  278. });
  279. await server.connected;
  280. server.send('foo');
  281. expect(onMessage).toHaveBeenCalledTimes(1);
  282. expect(onMessage).toHaveBeenCalledWith(expect.objectContaining({ data: 'foo' }));
  283. });
  284. });
  285. });