|
|
@@ -0,0 +1,85 @@
|
|
|
+import { act, render } from '@testing-library/react';
|
|
|
+import React from 'react';
|
|
|
+
|
|
|
+import { stateSet } from '../actions';
|
|
|
+import { masterStateUpdateTimeout } from '../constants/system';
|
|
|
+
|
|
|
+import { useMaster } from './master';
|
|
|
+
|
|
|
+describe(useMaster.name, () => {
|
|
|
+ const dispatch = jest.fn();
|
|
|
+
|
|
|
+ const TestComponent: React.FC<{ master: string; myClientName: string }> = ({
|
|
|
+ master,
|
|
|
+ myClientName,
|
|
|
+ }) => {
|
|
|
+ useMaster(dispatch, master, myClientName);
|
|
|
+ return null;
|
|
|
+ };
|
|
|
+
|
|
|
+ describe('when there is no master initially', () => {
|
|
|
+ it('should take control of master', () => {
|
|
|
+ expect.assertions(2);
|
|
|
+ const { unmount } = render(<TestComponent master="" myClientName="my-client-name" />);
|
|
|
+
|
|
|
+ expect(dispatch).toHaveBeenCalledTimes(1);
|
|
|
+ expect(dispatch).toHaveBeenCalledWith(stateSet({ master: 'my-client-name' }));
|
|
|
+
|
|
|
+ unmount();
|
|
|
+ });
|
|
|
+ });
|
|
|
+
|
|
|
+ describe('when the client is master', () => {
|
|
|
+ it('should continually refresh the server with the current state', () => {
|
|
|
+ expect.assertions(6);
|
|
|
+ const clock = jest.useFakeTimers();
|
|
|
+ const { unmount } = render(
|
|
|
+ <TestComponent master="the-master-client" myClientName="the-master-client" />,
|
|
|
+ );
|
|
|
+
|
|
|
+ act(() => {
|
|
|
+ clock.runTimersToTime(masterStateUpdateTimeout - 1);
|
|
|
+ });
|
|
|
+
|
|
|
+ expect(dispatch).toHaveBeenCalledTimes(0);
|
|
|
+ act(() => {
|
|
|
+ clock.runTimersToTime(1);
|
|
|
+ });
|
|
|
+
|
|
|
+ expect(dispatch).toHaveBeenCalledTimes(1);
|
|
|
+ expect(dispatch).toHaveBeenCalledWith(stateSet());
|
|
|
+
|
|
|
+ dispatch.mockClear();
|
|
|
+ expect(dispatch).toHaveBeenCalledTimes(0);
|
|
|
+
|
|
|
+ act(() => {
|
|
|
+ clock.runTimersToTime(masterStateUpdateTimeout);
|
|
|
+ });
|
|
|
+
|
|
|
+ expect(dispatch).toHaveBeenCalledTimes(1);
|
|
|
+ expect(dispatch).toHaveBeenCalledWith(stateSet());
|
|
|
+
|
|
|
+ unmount();
|
|
|
+ jest.useRealTimers();
|
|
|
+ });
|
|
|
+ });
|
|
|
+
|
|
|
+ describe('when the client is a slave', () => {
|
|
|
+ it('should not send state updates periodically', () => {
|
|
|
+ expect.assertions(1);
|
|
|
+ const clock = jest.useFakeTimers();
|
|
|
+ const { unmount } = render(
|
|
|
+ <TestComponent master="the-master-client" myClientName="my-client-name" />,
|
|
|
+ );
|
|
|
+
|
|
|
+ act(() => {
|
|
|
+ clock.runTimersToTime(masterStateUpdateTimeout);
|
|
|
+ });
|
|
|
+
|
|
|
+ expect(dispatch).not.toHaveBeenCalled();
|
|
|
+
|
|
|
+ unmount();
|
|
|
+ jest.useRealTimers();
|
|
|
+ });
|
|
|
+ });
|
|
|
+});
|