vim.spec.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { act, fireEvent, render } from '@testing-library/react';
  2. import React, { Dispatch } from 'react';
  3. import { ActionKeyPressed, ActionTypeKeyPressed, useVimBindings } from './vim';
  4. describe(useVimBindings.name, () => {
  5. const TestComponent: React.FC<{ dispatch: Dispatch<ActionKeyPressed>; skip?: boolean }> = ({
  6. dispatch,
  7. skip,
  8. }) => {
  9. useVimBindings(dispatch, skip);
  10. return null;
  11. };
  12. const dispatch = jest.fn();
  13. describe('when a key is pressed', () => {
  14. it('should dispatch a KeyPress action', () => {
  15. expect.assertions(2);
  16. jest.useFakeTimers();
  17. render(<TestComponent dispatch={dispatch} />);
  18. expect(dispatch).not.toHaveBeenCalled();
  19. act(() => {
  20. fireEvent.keyDown(window, {
  21. key: 'Tab',
  22. });
  23. });
  24. expect(dispatch).toHaveBeenCalledWith({ type: ActionTypeKeyPressed, key: 'Tab' });
  25. jest.useRealTimers();
  26. });
  27. });
  28. describe('when the key is unhandled', () => {
  29. it('should not dispatch anything', () => {
  30. expect.assertions(2);
  31. jest.useFakeTimers();
  32. render(<TestComponent dispatch={dispatch} />);
  33. expect(dispatch).not.toHaveBeenCalled();
  34. act(() => {
  35. fireEvent.keyDown(window, {
  36. key: '@',
  37. });
  38. });
  39. act(() => {
  40. jest.runAllTimers();
  41. });
  42. expect(dispatch).not.toHaveBeenCalled();
  43. jest.useRealTimers();
  44. });
  45. });
  46. describe('when skipping', () => {
  47. it('should not listen to any keys', () => {
  48. expect.assertions(1);
  49. jest.useFakeTimers();
  50. render(<TestComponent dispatch={dispatch} skip={true} />);
  51. act(() => {
  52. fireEvent.keyDown(window, {
  53. key: 'Tab',
  54. });
  55. });
  56. act(() => {
  57. jest.runAllTimers();
  58. });
  59. expect(dispatch).not.toHaveBeenCalled();
  60. jest.useRealTimers();
  61. });
  62. });
  63. });