@testing-library/react-hooks#act JavaScript Examples

The following examples show how to use @testing-library/react-hooks#act. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: toast-tests.jest.js    From monday-ui-react-core with MIT License 6 votes vote down vote up
describe("Toast tests", () => {
  it("calls onClose when click on close button", () => {
    const onCloseMock = jest.fn();
    const toast = renderComponent({
      open: true,
      onClose: onCloseMock
    });
    const closeButton = toast.getByLabelText("close-toast");

    act(() => {
      fireEvent.click(closeButton);
    });

    expect(onCloseMock.mock.calls.length).toBe(1);
  });

  it("calls onClose after 1S when autoHideDuration=1000", () => {
    const onCloseMock = jest.fn();
    renderComponent({
      onClose: onCloseMock,
      autoHideDuration: 1000,
      open: true
    });
    jest.useFakeTimers();
    expect(onCloseMock.mock.calls.length).toHaveBeenCalledTimes;
  });

  it("calls onClick when clicking on attached button to the toast", () => {
    const onClickMock = jest.fn();
    renderComponent({
      open: true,
      actions: [{ type: Toast.actionTypes.BUTTON, key: 1, content: "Button", onClick: onClickMock }]
    });
    expect(onClickMock.mock.calls.length).toHaveBeenCalledTimes;
  });
});
Example #2
Source File: useConnectModa.spec.js    From rainbow-modules with MIT License 6 votes vote down vote up
describe('useConnectModal', () => {
    it('should return initialDefaultProps', () => {
        const { result } = renderHook(() => useConnectModal('test'));
        expect(result.current).toEqual(initialDefaultProps);
    });
    it('should return combination initialDefaultProps with second parameter', () => {
        const foo = { bar: 'baz', title: 'test' };
        const { result } = renderHook(() => useConnectModal('test', foo));
        expect(result.current).toEqual({ ...initialDefaultProps, ...foo });
    });
    it('should return object passed in setProps', async () => {
        const foo = { bar: 'baz', title: 'test' };
        const { result } = renderHook(() => useConnectModal('test'));
        const [, setProps] = store.get('test');
        act(() => {
            setProps(foo);
        });
        expect(result.current).toEqual(foo);
    });
});
Example #3
Source File: usePrevious.test.js    From tonic-ui with MIT License 6 votes vote down vote up
describe('usePrevious', () => {
  it('should be defined', () => {
    expect(usePrevious).toBeDefined();
  });

  it('should return previous state', () => {
    const { result } = renderHook(() => {
      const [count, setCount] = useState(0);
      return {
        count,
        setCount,
        prevCount: usePrevious(count),
      };
    });
    expect(result.current.prevCount).toBe(undefined);

    act(() => {
      result.current.setCount(2);
    });
    expect(result.current.prevCount).toBe(0);

    act(() => {
      result.current.setCount(4);
    });
    expect(result.current.prevCount).toBe(2);

    act(() => {
      result.current.setCount(6);
    });
    expect(result.current.prevCount).toBe(4);
  });
});
Example #4
Source File: useAuth.js    From plataforma-sabia with MIT License 6 votes vote down vote up
describe('userAuth', () => {
	it('can setUser and logout', () => {
		const { result } = renderHook(() => useAuth(), { wrapper });

		expect(result.current.user).toEqual({});

		act(() => {
			result.current.setUser(testUser);
		});

		expect(result.current.user).toEqual(testUser);

		act(() => {
			result.current.logout();
		});

		expect(result.current.user).toEqual({});
	});
});
Example #5
Source File: useToggle.test.js    From tonic-ui with MIT License 6 votes vote down vote up
describe('useToggle', () => {
  it('should be defined', () => {
    expect(useToggle).toBeDefined();
  });

  it('should toggle boolean state', () => {
    const { result } = renderHook(() => useToggle(false));
    expect(result.current[0]).toBe(false);

    act(() => {
      result.current[1]();
    });
    expect(result.current[0]).toBe(true);

    act(() => {
      result.current[1]();
    });
    expect(result.current[0]).toBe(false);
  });

  it('should set toggle state to the given value', () => {
    const { result } = renderHook(() => useToggle(true));
    expect(result.current[0]).toBe(true);

    act(() => {
      result.current[1](true);
    });
    expect(result.current[0]).toBe(true);

    act(() => {
      result.current[1](false);
    });
    expect(result.current[0]).toBe(false);
  });
});
Example #6
Source File: use-wishlist.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('use-wishlist tests', () => {
  let wrap;
  let res;
  beforeEach(() => {
    wrap = renderHook(useWishlist);
  });

  it('should add item to wishlist', () => {
    act(() => {
      wrap.result.current.wishlistOperations.addToWishlist(mockItem);
    });

    expect(wrap.result.current.wishlist).toContain(mockItem);
  });

  it('should check is item in wishlist', () => {
    act(() => {
      res = wrap.result.current.isInWishlist(mockItem);
    });

    expect(res).toEqual(mockItem);
  });

  it('should remove item from wishlist', () => {
    act(() => {
      wrap.result.current.wishlistOperations.removeFromWishlist(mockItem);
    });

    expect(wrap.result.current.wishlist).toHaveLength(0);
  });
});
Example #7
Source File: index.test.js    From react-fluid-table with MIT License 6 votes vote down vote up
describe('useMyHook', () => {
  it('updates every second', () => {
    const { result } = renderHook(() => useMyHook());

    expect(result.current).toBe(0);

    // Fast-forward 1sec
    act(() => {
      jest.advanceTimersByTime(1000);
    });

    // Check after total 1 sec
    expect(result.current).toBe(1);

    // Fast-forward 1 more sec
    act(() => {
      jest.advanceTimersByTime(1000);
    });

    // Check after total 2 sec
    expect(result.current).toBe(2);
  })
})
Example #8
Source File: useCopyToClipboard.test.js    From tonic-ui with MIT License 5 votes vote down vote up
describe('useCopyToClipboard', () => {
  const consoleErrorSpy = jest.spyOn(global.console, 'error').mockImplementation(() => {});
  const originalClipboard = global.navigator.clipboard;

  beforeEach(() => {
    let clipboardData = '';
    const mockClipboard = {
      writeText: jest.fn(data => {
        clipboardData = data;
        return Promise.resolve(clipboardData);
      }),
      readText: jest.fn(() => clipboardData),
    };
    global.navigator.clipboard = mockClipboard;
  });

  afterEach(() => {
    consoleErrorSpy.mockRestore();
  });

  afterAll(() => {
    global.navigator.clipboard = originalClipboard;
  });

  it('should be defined', () => {
    expect(useCopyToClipboard).toBeDefined();
  });

  it('should copy a value to clipboard', async () => {
    const testValue = 'test';
    const { result } = renderHook(() => useCopyToClipboard());
    let [value, copyToClipboard] = result.current;
    expect(value).toBeUndefined();
    await act(async () => {
      const ok = await copyToClipboard(testValue);
      expect(ok).toBe(true);
    });
    expect(global.navigator.clipboard.writeText).toHaveBeenCalledTimes(1);
    expect(global.navigator.clipboard.writeText).toHaveBeenCalledWith(testValue);
    [value] = result.current;
    expect(value).toBe(testValue);
  });

  it('should console error if clipboard not supported', async () => {
    // clipboard not supported
    global.navigator.clipboard = undefined;

    const testValue = 'test';
    const { result } = renderHook(() => useCopyToClipboard());
    let [value, copyToClipboard] = result.current;
    expect(value).toBeUndefined();
    await act(async () => {
      const ok = await copyToClipboard(testValue);
      expect(ok).toBe(false);
    });
    expect(consoleErrorSpy).toBeCalled();
    [value] = result.current;
    expect(value).toBeUndefined();
  });

  it('should console error if clipboard write failed', async () => {
    // clipboard write failed
    global.navigator.clipboard.writeText = jest.fn(() => {
      throw new Error();
    });

    const testValue = 'test';
    const { result } = renderHook(() => useCopyToClipboard());
    let [value, copyToClipboard] = result.current;
    expect(value).toBeUndefined();
    await act(async () => {
      const ok = await copyToClipboard(testValue);
      expect(ok).toBe(false);
    });
    expect(consoleErrorSpy).toBeCalled();
    expect(global.navigator.clipboard.writeText).toBeCalled();
    [value] = result.current;
    expect(value).toBeUndefined();
  });
});
Example #9
Source File: tipseen-tests.jest.js    From monday-ui-react-core with MIT License 5 votes vote down vote up
describe("Integration Tests", () => {
  describe("Tipseen tests", () => {
    it("call onClose function when click on close button", () => {
      const onClickMock = jest.fn();
      const { getByLabelText } = render(
        <Tipseen onClose={onClickMock}>
          <div />
        </Tipseen>
      );
      fireEvent.click(getByLabelText("Close"));

      waitFor(() => {
        expect(onClickMock.mock.calls.length).toBe(1);
      });
    });
  });

  describe("Tipseen content tests", () => {
    it("call onDismiss function when click on dismiss button", () => {
      const onDismissMock = jest.fn();
      const { getByText } = render(
        <TipseenContent isDismissHidden={false} onDismiss={onDismissMock}>
          content
        </TipseenContent>
      );
      const dismissButton = getByText(DISMISS_BUTTON_TEXT);

      act(() => {
        fireEvent.click(dismissButton);
      });
      expect(onDismissMock.mock.calls.length).toBe(1);
    });

    it("call onSubmit function when click on dismiss button", () => {
      const onSubmitMock = jest.fn();
      const { getByText } = render(<TipseenContent onSubmit={onSubmitMock}>content</TipseenContent>);
      const submitButton = getByText(SUBMIT_BUTTON_TEXT);

      act(() => {
        fireEvent.click(submitButton);
      });
      expect(onSubmitMock.mock.calls.length).toBe(1);
    });
  });
});
Example #10
Source File: useEffectOnceWhen.test.js    From tonic-ui with MIT License 5 votes vote down vote up
describe('useEffectOnceWhen', () => {
  const useTestHook = () => {
    const [value, setValue] = useState(0);
    const [isEnabled, setIsEnabled] = useState(false);
    useEffectOnceWhen(() => {
      setValue(value => value + 1);
    }, isEnabled);

    return { value, setIsEnabled };
  };

  it('should be defined', () => {
    expect(useEffectOnceWhen).toBeDefined();
  });

  it('runs immediately after condition is met', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    act(() => {
      result.current.setIsEnabled(true);
    });
    expect(result.current.value).toBe(1);
  });

  it('does not run twice after condition is met', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    act(() => {
      result.current.setIsEnabled(true);
    });
    expect(result.current.value).toBe(1);
    act(() => {
      result.current.setIsEnabled(false);
    });
    act(() => {
      result.current.setIsEnabled(true);
    });
    expect(result.current.value).toBe(1);
  });
});
Example #11
Source File: index.test.js    From react-use-opentok with MIT License 5 votes vote down vote up
describe('test session event handler', () => {
  it('handleConnectionCreated and handleConnectionDestroyed', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));
    [opentokProps, opentokMethods] = result.current;

    // handleConnectionCreated
    expect(opentokProps.connections).toEqual([]);
    act(() =>
      opentokProps.session.dispatch('connectionCreated', {
        connection: MOCK_CONNECTION,
      })
    );
    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.connections).toEqual([MOCK_CONNECTION]);

    // handleConnectionDestroyed
    act(() =>
      opentokProps.session.dispatch('connectionDestroyed', {
        connection: MOCK_CONNECTION,
      })
    );

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.connections).toEqual([]);
  });

  it('handleStreamCreated and handleStreamDestroyed', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    // handleStreamCreated
    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.streams).toEqual([]);
    act(() =>
      opentokProps.session.dispatch('streamCreated', {
        stream: MOCK_STREAM,
      })
    );
    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.streams).toEqual([MOCK_STREAM]);

    // handleStreamDestroyed
    act(() =>
      opentokProps.session.dispatch('streamDestroyed', {
        stream: MOCK_STREAM,
      })
    );

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.streams).toEqual([]);
  });
});
Example #12
Source File: useActiveDescendantListFocus.jest.js    From monday-ui-react-core with MIT License 5 votes vote down vote up
function runListUnitTest(isHorizontal) {
  const moveForwardKey = isHorizontal ? "{arrowRight}" : "{arrowDown}";
  const oppositeMoveForwardKey = !isHorizontal ? "{arrowRight}" : "{arrowDown}";
  it("should trigger onClick when focused element has natural focus and user navigate to item and press enter", async () => {
    const onItemClick = jest.fn();
    renderHookForTest({ onItemClick, isHorizontal });

    act(() => {
      // set focus on the list's element which in charge on natural focus element
      element.focus();
      // move visual focus to first item
      userEvent.keyboard(moveForwardKey);
    });

    act(() => {
      // Trigger on click by press enter
      userEvent.keyboard("{Enter}");
    });

    expect(onItemClick).toHaveBeenCalledTimes(1);
    expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({}), 0);
  });

  it("should not trigger onClick when focused element does not have natural focus and user navigate to item and press enter", async () => {
    const onItemClick = jest.fn();
    renderHookForTest({ onItemClick, isHorizontal });

    act(() => {
      // move visual focus to first item
      userEvent.keyboard(moveForwardKey);
    });

    act(() =>
      // Trigger on click by press enter
      userEvent.keyboard("{Enter}")
    );

    expect(onItemClick).toHaveBeenCalledTimes(0);
  });

  it("should skip not selectable item when user try to navigate to it", async () => {
    const onItemClick = jest.fn();
    const isItemSelectable = i => i !== 0;
    const { result } = renderHookForTest({ onItemClick, isItemSelectable, isHorizontal });

    act(() => {
      // set focus on the list's element which in charge on natural focus element
      element.focus();

      // move visual focus to first item
      userEvent.keyboard(moveForwardKey);
    });

    expect(result.current.visualFocusItemIndex).toEqual(1);
  });

  it("should not navigate to next item when user try to navigate by using keys for the  opposite dimension to the list dimension ", async () => {
    const onItemClick = jest.fn();
    const { result } = renderHookForTest({ onItemClick, isHorizontal });

    act(() => {
      // set focus on the list's element which in charge on natural focus element
      element.focus();

      // move visual focus to first item
      userEvent.keyboard(oppositeMoveForwardKey);
    });

    expect(result.current.visualFocusItemIndex === 0).toBeFalsy();
  });
}
Example #13
Source File: useSnackbar.native.test.js    From blade with MIT License 5 votes vote down vote up
describe('useSnackbar hook', () => {
  it('show the snackbar', () => {
    const { result } = renderHook(() => useSnackbar(), {
      wrapper: Wrapper,
    });
    expect(result.current.isVisible).toBe(false);
    act(() => {
      result.current.show({
        title: 'Snackbar text here',
        autoHide: false,
      });
    });
    expect(result.current.isVisible).toBe(true);
  });

  it('close the snackbar', () => {
    const { result } = renderHook(() => useSnackbar(), {
      wrapper: Wrapper,
    });
    expect(result.current.isVisible).toBe(false);
    act(() => {
      result.current.show({
        title: 'Snackbar text here',
        autoHide: false,
      });
    });
    expect(result.current.isVisible).toBe(true);
    act(() => {
      result.current.close();
    });
    expect(result.current.isVisible).toBe(false);
  });

  it('auto-hide the snackbar', () => {
    jest.useFakeTimers(); // Uses fake timer to resolve setTimeout
    const { result } = renderHook(() => useSnackbar(), {
      wrapper: Wrapper,
    });
    expect(result.current.isVisible).toBe(false);
    act(() => {
      result.current.show({
        title: 'Snackbar text here',
        autoHide: true,
      });
    });
    expect(result.current.isVisible).toBe(true);
    act(() => {
      jest.runAllTimers(); // Resolve auto hide timer
    });
    expect(result.current.isVisible).toBe(false);
  });
});
Example #14
Source File: useLocalStorage.test.js    From js-miniapp with MIT License 5 votes vote down vote up
test('should save passed in value to local storage', () => {
  const { result } = renderHook(() => useLocalStorage('test', 'initial-value'));
  act(() => {
    result.current[1]('input-value');
  });
  expect(result.current[0]).toBe('input-value');
});
Example #15
Source File: index.test.js    From react-use-opentok with MIT License 5 votes vote down vote up
describe('session initialization and connection', () => {
  it('initSession', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;

    expect(opentokProps.session).toBeUndefined();
    expect(opentokProps.isSessionInitialized).toBeFalsy();
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.session).toBeDefined();
    expect(opentokProps.isSessionInitialized).toBeTruthy();
  });

  it('connectSession', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;

    try {
      await act(() => opentokMethods.connectSession(MOCK_CREDENTIALS.token));
    } catch (error) {
      expect(error).toMatch(/session/);
    }

    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.isSessionConnected).toBeFalsy();
    expect(opentokProps.connectionId).toBeUndefined();

    try {
      await act(() => opentokMethods.connectSession());
    } catch (error) {
      expect(error).toMatch(/token/);
    }

    [opentokProps, opentokMethods] = result.current;
    await act(() =>
      opentokMethods.connectSession(
        MOCK_CREDENTIALS.token,
        opentokProps.session
      )
    );
    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.isSessionConnected).toBeTruthy();
    expect(opentokProps.connectionId).toEqual(expect.any(String));
  });

  it('initSessionAndConnect', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;
    // expect(1).toBe(1);
    expect(opentokProps.session).toBeUndefined();
    expect(opentokProps.isSessionConnected).toBeFalsy();
    expect(opentokProps.connectionId).toBeUndefined();

    await act(() => opentokMethods.initSessionAndConnect(MOCK_CREDENTIALS));
    // [opentokProps, opentokMethods] = result.current;

    // expect(opentokProps.session).toBeDefined();
    // expect(opentokProps.isSessionConnected).toBeTruthy();
    // expect(opentokProps.connectionId).toEqual(expect.any(String));
  });
});
Example #16
Source File: useGeoLocation.test.js    From js-miniapp with MIT License 5 votes vote down vote up
describe('useGeoLocation', () => {
  let result;
  const dummyCoordinates = {
    latitude: 51.1,
    longitude: 45.3,
  };
  const mockGeolocation = {
    watchPosition: jest.fn(),
    clearWatch: jest.fn(),
    getCurrentPosition: jest.fn().mockImplementation((success) =>
      Promise.resolve(
        success({
          coords: dummyCoordinates,
        })
      )
    ),
  };
  beforeEach(() => {
    result = renderHook(() => useGeoLocation()).result;
    navigator.geolocation = mockGeolocation;
    MiniApp.requestLocationPermission = jest.fn().mockResolvedValue('');
  });

  test('should initialize location hook', () => {
    const [state] = result.current;
    expect(state.isWatching).toEqual(false);
    expect(state.location).toBeUndefined();
  });

  test('should watch location coordinates when permission granted', async () => {
    MiniApp.requestLocationPermission = jest.fn().mockResolvedValue('');

    let [state, watch] = result.current;
    await act(() => watch());
    [state] = result.current;

    expect(state.isWatching).toEqual(true);
    expect(state.location).toEqual(dummyCoordinates);
  });

  test('should not watch location when permission not granted', async () => {
    MiniApp.requestLocationPermission = jest.fn().mockRejectedValue('');

    let [state, watch] = result.current;
    await act(() => watch());
    [state] = result.current;

    expect(state.isWatching).toEqual(false);
    expect(state.location).not.toEqual(dummyCoordinates);
  });

  test('should stop watching location coordinates', async () => {
    let [state, watch, unwatch] = result.current;
    await act(() => watch());
    [state] = result.current;
    expect(state.isWatching).toEqual(true);
    expect(state.location).toEqual(dummyCoordinates);
    act(() => unwatch());
    [state] = result.current;
    expect(state.isWatching).toEqual(false);
    expect(state.location).toBeUndefined();
  });
});
Example #17
Source File: use-session-event-handler.test.js    From react-use-opentok with MIT License 5 votes vote down vote up
describe('test useSessionEventHandler', () => {
  it('test for handle connectionCreated with correct parameters', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));
    [opentokProps, opentokMethods] = result.current;

    // NOTICE: remove all event listeners registered when rendering reactUseOpenTok
    sessionEvent.removeAllListeners('connectionCreated');
    const handleConnectionCreated = jest.fn();
    expect(handleConnectionCreated).not.toHaveBeenCalled();

    renderHook(() =>
      useSessionEventHandler(
        'connectionCreated',
        handleConnectionCreated,
        opentokProps.session
      )
    );

    act(() => opentokProps.session.dispatch('connectionCreated'));
    expect(handleConnectionCreated).toHaveBeenCalledTimes(1);
  });

  it('handle incorrect event type', async () => {
    const { result: reactUseOpentokResult } = renderHook(() =>
      reactUseOpentok()
    );
    let [opentokProps, opentokMethods] = reactUseOpentokResult.current;
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));
    [opentokProps, opentokMethods] = reactUseOpentokResult.current;

    // NOTICE: remove all event listeners registered when rendering reactUseOpenTok
    sessionEvent.removeAllListeners('connectionCreated');
    const handleConnectionCreated = jest.fn();

    const { result } = renderHook(() =>
      useSessionEventHandler(
        'THIS_EVENT_TYPE_IS_NOT_SUPPORTED',
        handleConnectionCreated,
        opentokProps.session
      )
    );

    act(() => opentokProps.session.dispatch('connectionCreated'));

    expect(() => result.current).toThrow();
  });

  it('handle incorrect eventHandler', async () => {
    const { result: reactUseOpentokResult } = renderHook(() =>
      reactUseOpentok()
    );
    let [opentokProps, opentokMethods] = reactUseOpentokResult.current;
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    [opentokProps, opentokMethods] = reactUseOpentokResult.current;
    expect(opentokProps.session).toBeDefined();

    // NOTICE: remove all event listeners registered when rendering reactUseOpenTok
    sessionEvent.removeAllListeners('connectionCreated');
    const handleConnectionCreated = 'THIS_EVENT_HANDLER_IS_NOT_FUNCTION';

    const { result } = renderHook(() =>
      useSessionEventHandler(
        'connectionCreated',
        handleConnectionCreated,
        opentokProps.session
      )
    );

    act(() => opentokProps.session.dispatch('connectionCreated'));

    expect(() => result.current).toThrow();
  });
});
Example #18
Source File: steps-tests.jest.js    From monday-ui-react-core with MIT License 5 votes vote down vote up
describe("Steps tests", () => {
  it("call onChangeIndexCallback when click on go back button and it does not disable", () => {
    const onClickMock = jest.fn();
    const steps = renderComponent({
      onChangeActiveStep: onClickMock,
      activeStepIndex: stepsContent.length - 1
    });
    const backwardButton = steps.getByText(BACK_DESCRIPTION);

    act(() => {
      fireEvent.click(backwardButton);
    });
    expect(onClickMock.mock.calls.length).toBe(1);
  });

  it("call onChangeIndexCallback when click on go forward button and it does not disable", () => {
    const onClickMock = jest.fn();
    const steps = renderComponent({
      onChangeActiveStep: onClickMock,
      activeStepIndex: 0
    });
    const forwardButton = steps.getByText(NEXT_DESCRIPTION);

    act(() => {
      fireEvent.click(forwardButton);
    });

    expect(onClickMock.mock.calls.length).toBe(1);
  });

  it("does not call onChangeIndexCallback when click on back button and when in first page", () => {
    const onClickMock = jest.fn();
    const steps = renderComponent({
      onChangeActiveStep: onClickMock,
      activeStepIndex: 0
    });
    const backwardButton = steps.getByText(BACK_DESCRIPTION);

    act(() => {
      fireEvent.click(backwardButton);
    });

    expect(onClickMock.mock.calls.length).toBe(0);
  });

  it("does not call onChangeIndexCallback when click on next button when in last page", () => {
    const onClickMock = jest.fn();
    const steps = renderComponent({
      onChangeActiveStep: onClickMock,
      activeStepIndex: stepsContent.length - 1
    });
    const forwardButton = steps.getByText(NEXT_DESCRIPTION);

    act(() => {
      fireEvent.click(forwardButton);
    });

    expect(onClickMock.mock.calls.length).toBe(0);
  });
});
Example #19
Source File: useOnceWhen.test.js    From tonic-ui with MIT License 5 votes vote down vote up
describe('useOnceWhen', () => {
  const useTestHook = () => {
    const [value, setValue] = useState(0);
    const callTimes = useRef(0);

    useOnceWhen(() => {
      callTimes.current++;
    }, (value > 0));

    return { value, setValue, callTimes };
  };

  it('should be defined', () => {
    expect(useOnceWhen).toBeDefined();
  });

  it('runs immediately before render if the condition is true', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    expect(result.current.callTimes.current).toBe(0);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(1);
    expect(result.current.callTimes.current).toBe(1);
  });

  it('does not run twice even if the condition is true', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    expect(result.current.callTimes.current).toBe(0);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(1);
    expect(result.current.callTimes.current).toBe(1);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(2);
    expect(result.current.callTimes.current).toBe(1);
  });
});
Example #20
Source File: menu.jest.js    From monday-ui-react-core with MIT License 5 votes vote down vote up
describe.skip("<Menu />", () => {
  afterEach(() => {
    cleanup();
  });

  it("calls onClick only for the selected menu item when using the mouse", () => {
    const menuComponent = renderComponent();

    const menuItem = menuComponent.getByText(menuItem1Name);

    act(() => {
      fireEvent.mouseOver(menuItem);
      jest.advanceTimersByTime(1000);
      fireEvent.click(menuItem);
    });

    jest.advanceTimersByTime(1000);
    expect(menuItem1OnClickMock.mock.calls.length).toBe(1);
    expect(menuItem2OnClickMock.mock.calls.length).toBe(0);
  });

  it("calls onClick only for the selected menu item when using the enter", () => {
    const menuComponent = renderComponent();
    const menuItem = menuComponent.getByText(menuItem1Name);

    act(() => {
      fireEvent.mouseOver(menuItem);
      jest.advanceTimersByTime(1000);
      fireEvent.keyUp(menuItem, { key: "Enter" });
    });

    jest.advanceTimersByTime(1000);
    expect(menuItem1OnClickMock.mock.calls.length).toBe(1);
    expect(menuItem2OnClickMock.mock.calls.length).toBe(0);
  });

  it("calls onClick only for the selected menu item when using keyboard", () => {
    const menuComponent = renderComponent();
    const menuElement = menuComponent.getByLabelText("menu");

    act(() => {
      fireEvent.keyUp(menuElement, { key: "ArrowDown" });
      jest.advanceTimersByTime(1000);
      fireEvent.keyUp(menuElement, { key: "Enter" });
    });

    jest.advanceTimersByTime(1000);
    expect(menuItem1OnClickMock.mock.calls.length).toBe(1);
    expect(menuItem2OnClickMock.mock.calls.length).toBe(0);
  });
});
Example #21
Source File: useOnce.test.js    From tonic-ui with MIT License 5 votes vote down vote up
describe('useOnce', () => {
  const useTestHook = () => {
    const [value, setValue] = useState(0);
    const callTimes = useRef(0);

    useOnce(() => {
      callTimes.current++;
    }, (value > 0));

    return { value, setValue, callTimes };
  };

  it('should be defined', () => {
    expect(useOnce).toBeDefined();
  });

  it('runs immediately before the first render', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    expect(result.current.callTimes.current).toBe(1);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(1);
    expect(result.current.callTimes.current).toBe(1);
  });

  it('does not run twice', () => {
    const { result } = renderHook(() => useTestHook());
    expect(result.current.value).toBe(0);
    expect(result.current.callTimes.current).toBe(1);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(1);
    expect(result.current.callTimes.current).toBe(1);
    act(() => {
      result.current.setValue(value => value + 1);
    });
    expect(result.current.value).toBe(2);
    expect(result.current.callTimes.current).toBe(1);
  });
});
Example #22
Source File: useExport.test.js    From tasks-frontend with Apache License 2.0 5 votes vote down vote up
describe('useExport', () => {
  let workingExporter = jest.fn(() => Promise.resolve(items));
  let defaultOptions;

  beforeEach(() => {
    defaultOptions = {
      columns,
    };
  });

  it('returns an export config toolbar config', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() => useExport(defaultOptions));
    expect(result.current.toolbarProps.exportConfig).toBeDefined();
    expect(result).toMatchSnapshot();
  });

  it('returns an export config toolbar config', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() =>
      useExport({
        ...defaultOptions,
        isDisabled: true,
      })
    );
    expect(result.current.toolbarProps.exportConfig.isDisabled).toBe(true);
  });

  it('calls the exporter via onSelect', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() => useExport(defaultOptions));

    act(() => {
      result.current.toolbarProps.exportConfig.onSelect(null, 'csv');
    });

    expect(defaultOptions.exporter).toHaveBeenCalled();

    act(() => {
      result.current.toolbarProps.exportConfig.onSelect(null, 'json');
    });

    expect(defaultOptions.exporter).toHaveBeenCalled();
  });
});
Example #23
Source File: useVisibleComponent.js    From plataforma-sabia with MIT License 5 votes vote down vote up
describe('useVisibleComponent', () => {
	it('should return the default values if initialState is not provided and the user did not click anywhere', () => {
		const { result } = renderHook(() => useVisibleComponent());

		expect(result.current[0].current).toBeNull();
		expect(result.current[1]).toBe(false);

		act(() => {
			result.current[2](true);
		});

		expect(result.current[1]).toBe(true);
	});

	it('should return falsy state only if the user clicks outside the component', () => {
		const { result } = renderHook(() => useVisibleComponent(true));

		expect(result.current[0].current).toBeNull();
		expect(result.current[1]).toBe(true);

		const onClickBtn1 = jest.fn();
		const onClickBtn2 = jest.fn();
		render(
			<>
				<button type="button" onClick={onClickBtn1} ref={result.current[0]}>
					WithRefButton
				</button>
				<button type="button" onClick={onClickBtn2}>
					WithoutRefButton
				</button>
			</>,
		);

		fireEvent.click(screen.getByRole('button', { name: /WithRefButton/i }));
		expect(onClickBtn1).toHaveBeenCalledTimes(1);
		expect(result.current[1]).toBe(true);

		act(() => {
			fireEvent.click(screen.getByRole('button', { name: /WithoutRefButton/i }));
		});
		expect(onClickBtn2).toHaveBeenCalledTimes(1);
		expect(result.current[1]).toBe(false);
	});
});
Example #24
Source File: usePaginate.test.js    From tasks-frontend with Apache License 2.0 5 votes vote down vote up
describe('usePaginate', () => {
  it('returns a paginate configuration', () => {
    const { result } = renderHook(() => usePaginate());
    expect(result).toMatchSnapshot();
  });

  it('returns a paginate configuration', () => {
    const { result } = renderHook(() => usePaginate());

    act(() => {
      result.current.setPage(2);
    });

    expect(result.current.toolbarProps.pagination.page).toBe(2);
  });

  it('returns a paginate configuration', () => {
    const { result } = renderHook(() => usePaginate({ perPage: 5 }));

    act(() => {
      result.current.setPage(1);
    });

    const paginatedItems = result.current.paginator(items);

    expect(paginatedItems).toMatchSnapshot();
    expect(paginatedItems.length).toBe(3);
    expect(paginatedItems[1]).toBe(items[1]);
  });

  it('returns page 1', () => {
    const { result } = renderHook(() => usePaginate());

    act(() => {
      result.current.setPage(-1);
    });

    expect(result.current.toolbarProps.pagination.page).toBe(1);
  });

  it('returns empty objection with pagination disabled', () => {
    let options = { pagination: false };
    const { result } = renderHook(() => usePaginate(options));

    expect(result.current).toEqual({});
  });
});
Example #25
Source File: debugCart.test.js    From use-shopping-cart with MIT License 5 votes vote down vote up
describe('<DebugCart>', () => {
  beforeEach(() => {
    const Wrapper = createWrapper()
    act(() => {
      render(
        <Wrapper>
          <DebugCart />
        </Wrapper>
      )
      return undefined
    })
  })

  it('should make a table of properties and values from the cart', async () => {
    const { cartDetails, ...remainingState } = expectedInitialCartState
    // console.log(cartDetails)
    const tableElement = await screen.findByRole('table')
    expect(tableElement).toBeVisible()
    const cartDetailsCell = await screen.findByRole('cell', {
      name: 'cartDetails'
    })
    expect(cartDetailsCell).toBeVisible()

    const logButton = await findByRole(
      cartDetailsCell.parentElement,
      'button',
      { name: /log value/i }
    )
    expect(logButton).toBeVisible()

    for (const property in remainingState) {
      const keyCell = await screen.findByRole('cell', { name: property })
      const valueCell = await getByRole(keyCell.parentElement, 'cell', {
        name: JSON.stringify(remainingState[property])
      })

      expect(keyCell).toBeVisible()
      expect(valueCell).toBeVisible()
    }
  })
})
Example #26
Source File: index.test.js    From use-infinite-scroll with MIT License 5 votes vote down vote up
describe('useInfiniteScroll', () => {
  let hook;
  let scrollerNode = document.createElement('div');
  let loaderNode = document.createElement('div');

  beforeEach(async () => {
    hook = renderHook(({ hasMore }) => useInfiniteScroll({ hasMore }), {
      initialProps: { hasMore: false },
    });
    const [, loaderRef, scrollerRef] = hook.result.current;
    loaderRef.current = loaderNode;
    scrollerRef.current = scrollerNode;

    hook.rerender({ hasMore: true });
  });

  it('first page should be 0', () => {
    const [page] = hook.result.current;
    expect(page).toBe(0);
  });

  it('should observe the loader node', () => {
    const observer = intersectionMockInstance(loaderNode);
    expect(observer).toBeDefined();
    expect(observer.observe).toHaveBeenCalledWith(loaderNode);
  });

  it('should switch to next page when reaching loaderNode intersection', () => {
    act(() => mockIsIntersecting(loaderNode, true));
    const [page] = hook.result.current;
    expect(page).toBe(1);
  });

  it('should disconnect when there are no more results', () => {
    const observer = intersectionMockInstance(loaderNode);
    expect(observer.disconnect).not.toHaveBeenCalled();

    hook.rerender({ hasMore: false });
    expect(observer.disconnect).toHaveBeenCalled();
  });
});
Example #27
Source File: loadmore.test.js    From 7-react-admin-ts with MIT License 5 votes vote down vote up
describe('useRequest', () => {
  const originalError = console.error;
  beforeAll(() => {
    jest.useFakeTimers();
    console.error = (...args) => {
      if (/Warning.*not wrapped in act/.test(args[0])) {
        return;
      }
      originalError.call(console, ...args);
    };
  });
  afterAll(() => {
    console.error = originalError;
  });

  const asyncFn = ({ pageSize, offset }) =>
    new Promise(resolve => {
      resolve({
        total: dataSource.length,
        list: dataSource.slice(offset, offset + pageSize),
      });
    });

  const setUp = (service, options) => renderHook(() => useRequest(service, options))

  let hook;

  it('useRequest loadMore should work', async () => {
    act(() => {
      hook = setUp(d => asyncFn({
        offset: d ? d.list.length : 0,
        pageSize: 3,
      }), {
        loadMore: true,
        isNoMore: d => (d ? d.total <= d.list.length : false)
      });
    });
    expect(hook.result.current.loading).toEqual(true);
    await hook.waitForNextUpdate();

    expect(hook.result.current.loading).toEqual(false);
    expect(hook.result.current.noMore).toEqual(false);
    expect(hook.result.current.data.list.length).toEqual(3);

    act(() => {
      hook.result.current.loadMore();
    });
    expect(hook.result.current.loading).toEqual(false);
    expect(hook.result.current.loadingMore).toEqual(true);
    expect(hook.result.current.data.list.length).toEqual(3);
    await hook.waitForNextUpdate();
    expect(hook.result.current.loadingMore).toEqual(false);
    expect(hook.result.current.data.list.length).toEqual(6);
    act(() => {
      hook.result.current.loadMore();
    });
    await hook.waitForNextUpdate();
    act(() => {
      hook.result.current.loadMore();
    });
    expect(hook.result.current.loadingMore).toEqual(true);
    expect(hook.result.current.data.list.length).toEqual(9);
    await hook.waitForNextUpdate();
    expect(hook.result.current.loadingMore).toEqual(false);
    expect(hook.result.current.data.list.length).toEqual(10);
    expect(hook.result.current.noMore).toEqual(true);
    act(() => {
      hook.result.current.reload();
    });
    expect(hook.result.current.loading).toEqual(true);
    await hook.waitForNextUpdate();
    expect(hook.result.current.data.list.length).toEqual(3);
    hook.unmount();
  });
});
Example #28
Source File: useAppReview-test.js    From react-native-in-app-review with MIT License 5 votes vote down vote up
describe('App Review Hook Behavoir', () => {
  const currentDate = new Date('2021-01-10T11:01:58.135Z');
  global.Date = class extends Date {
    constructor(date) {
      if (date) {
        return super(date);
      }

      return currentDate;
    }
  };
  afterAll(() => {
    jest.resetModule();
  });

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should trigger InAppReview in cross platform in first time', async () => {
    const expectItemSavedToAsync = ['in_App_Review', new Date().toString()];

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());
    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');
    expect(AsyncStorage.setItem).toHaveBeenCalledWith(
      ...expectItemSavedToAsync,
    );

    expect(InAppReview.RequestInAppReview).toHaveBeenCalled();
  });

  it('should not trigger InAppReview before 15 days user already get InAppReview', async () => {
    const expectedItem = '2021-01-05';
    jest
      .spyOn(AsyncStorage, 'getItem')
      .mockReturnValueOnce(Promise.resolve(expectedItem));

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());
    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');

    expect(InAppReview.RequestInAppReview).not.toHaveBeenCalled();
  });

  it('should trigger InAppReview after 15 days user get InAppReview and save Date to async Storage', async () => {
    const expectedItem = '2021-01-26';
    const expectItemSavedToAsync = ['in_App_Review', new Date().toString()];

    jest
      .spyOn(AsyncStorage, 'getItem')
      .mockReturnValueOnce(Promise.resolve(expectedItem));

    jest.spyOn(AsyncStorage, 'setItem');

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());

    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');
    expect(AsyncStorage.setItem).toHaveBeenCalledWith(
      ...expectItemSavedToAsync,
    );
    expect(InAppReview.RequestInAppReview).toHaveBeenCalled();
  });
});
Example #29
Source File: pagination.test.js    From 7-react-admin-ts with MIT License 4 votes vote down vote up
describe('useRequest', () => {
  const originalError = console.error;
  beforeAll(() => {
    jest.useFakeTimers();
    console.error = (...args) => {
      if (/Warning.*not wrapped in act/.test(args[0])) {
        return;
      }
      originalError.call(console, ...args);
    };
  });
  afterAll(() => {
    console.error = originalError;
  });

  let queryArgs;
  const asyncFn = query => {
    queryArgs = query;
    return Promise.resolve({
      current: query.current,
      total: 20,
      pageSize: query.pageSize,
      list: [],
    });
  };

  const setUp = (service, options) => renderHook(() => useRequest(service, options))

  let hook;

  it('should fetch after first render', async () => {
    queryArgs = undefined;
    act(() => {
      hook = setUp(asyncFn, {
        paginated: true
      });
    });
    expect(hook.result.current.tableProps.loading).toEqual(true);
    expect(queryArgs.current).toEqual(1);
    expect(queryArgs.pageSize).toEqual(10);
    await hook.waitForNextUpdate();

    expect(hook.result.current.tableProps.loading).toEqual(false);
    expect(hook.result.current.tableProps.pagination.current).toEqual(1);
    expect(hook.result.current.tableProps.pagination.pageSize).toEqual(10);
    expect(hook.result.current.tableProps.pagination.total).toEqual(20);

    expect(hook.result.current.pagination.current).toEqual(1);
    expect(hook.result.current.pagination.pageSize).toEqual(10);
    expect(hook.result.current.pagination.total).toEqual(20);
  });

  it('should sorter, filters work', async () => {
    queryArgs = undefined;
    act(() => {
      hook = setUp(asyncFn, {
        paginated: true
      });
    });
    await hook.waitForNextUpdate();
    act(() => {
      hook.result.current.tableProps.onChange({
        current: 2,
        pageSize: 5,
      });
    });
    await hook.waitForNextUpdate();
    expect(hook.result.current.tableProps.pagination.current).toEqual(2);
    /* 改变 filter, sorter */
    act(() => {
      hook.result.current.tableProps.onChange(
        {
          current: 2,
          pageSize: 5,
        },
        { gender: ['male'] },
        { field: 'email', order: 'ascend' },
      );
    });
    await hook.waitForNextUpdate();
    expect(queryArgs.current).toEqual(2);
    expect(queryArgs.pageSize).toEqual(5);
    expect(queryArgs.sorter.field).toEqual('email');
    expect(queryArgs.sorter.order).toEqual('ascend');
    expect(queryArgs.filters.gender[0]).toEqual('male');
  });
});