@testing-library/react-hooks#act TypeScript 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: useGameEventProvider.test.ts    From overwolf-hooks with MIT License 6 votes vote down vote up
describe('useGameEventProvider values', () => {
  it('should return undefined when there are no required features', () => {
    const { result } = renderHook(() =>
      useGameEventProvider({ displayLog: true }),
    )
    const [{ event, info }] = result.current
    expect(event).toBeUndefined()
    expect(info).toBeUndefined()
  })
  it('should return gameEvent value in first update after set required features', () => {
    const { result } = renderHook(() =>
      useGameEventProvider<{ info: string }, { event: string }>({
        displayLog: true,
      }),
    )
    const [initialGameData, setRequiredFeatures] = result.current
    act(() => {
      setRequiredFeatures(['kill', 'match'])
    })

    const [gameData] = result.current

    expect(initialGameData).toEqual({ event: undefined, info: undefined })
    expect(gameData).toEqual({ event: ['event-test'], info: 'info-test' })
  })
})
Example #2
Source File: login.hooks.spec.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
describe('useLogin specs', () => {
  it('should return an object: credential with default values and setCredential a function when it calls it', () => {
    // Arrange

    // Act
    const { result } = renderHook(() => useLogin());

    // Assert
    const defaultCredential: Credential = { name: '', password: '' };
    expect(result.current.credential).toEqual(defaultCredential);
    expect(result.current.setCredential).toEqual(expect.any(Function));
  });

  it('should update credential when it calls setCredential', () => {
    // Arrange
    const newCredential: Credential = { name: 'admin', password: 'test' };

    // Act
    const { result } = renderHook(() => useLogin());

    act(() => {
      result.current.setCredential(newCredential);
    });

    // Assert
    expect(result.current.credential).toEqual(newCredential);
  });
});
Example #3
Source File: useSpreadSheet-spec.ts    From S2 with MIT License 6 votes vote down vote up
describe('useSpreadSheet tests', () => {
  const container = getContainer();
  const props: SheetComponentsProps = {
    spreadsheet: () => new PivotSheet(container, mockDataConfig, s2Options),
    options: s2Options,
    dataCfg: mockDataConfig,
  };

  test('should build spreadSheet', () => {
    const { result } = renderHook(() =>
      useSpreadSheet({ ...props, sheetType: 'pivot' }),
    );
    expect(result.current.s2Ref).toBeDefined();
  });

  test('should cannot change table size when width or height updated and disable adaptive', () => {
    const { result } = renderHook(() =>
      useSpreadSheet({ ...props, sheetType: 'pivot', adaptive: false }),
    );
    const s2 = result.current.s2Ref.current;

    expect(s2.options.width).toEqual(s2Options.width);
    expect(s2.options.height).toEqual(s2Options.height);
    act(() => {
      s2.setOptions({ width: 300, height: 400 });
    });

    const canvas = s2.container.get('el') as HTMLCanvasElement;
    expect(s2.options.width).toEqual(300);
    expect(s2.options.height).toEqual(400);

    expect(canvas.style.width).toEqual(`200px`);
    expect(canvas.style.height).toEqual(`200px`);
  });
});
Example #4
Source File: SecretsContext.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('SecretsContext', () => {
  it('should allow the setting of secrets in the context', async () => {
    const { result } = renderHook(
      () => ({
        hook: useTemplateSecrets(),
        context: useContext(SecretsContext),
      }),
      {
        wrapper: ({ children }) => (
          <SecretsContextProvider>{children}</SecretsContextProvider>
        ),
      },
    );
    expect(result.current.context?.secrets.foo).toEqual(undefined);

    act(() => result.current.hook.setSecrets({ foo: 'bar' }));

    expect(result.current.context?.secrets.foo).toEqual('bar');
  });
});
Example #5
Source File: main-callback.test.ts    From sdc-ide with MIT License 6 votes vote down vote up
test('saveQuestionnaireFHIR', async () => {
    await setup();
    const { result, waitFor } = renderHook(() => useMain('test-1'));

    await waitFor(() => {
        ensure(result.current.questionnaireRD);
    });
    await act(async () => {
        await result.current.saveQuestionnaireFHIR(questionnaireTest1FHIRNew as Questionnaire);
    });
    await waitFor(() => {
        const qUpdated = ensure(result.current.questionnaireRD);
        expect(qUpdated.item?.[0].text).toBe('First Name 1');
    });
});
Example #6
Source File: useFetchResource.test.tsx    From ke with MIT License 6 votes vote down vote up
test('fetch должен вызываться с параметром url если он пеередан в конфиг', async () => {
  const axiosMock = jest.fn(() => Promise.resolve({ data: {} }))
  const config: Partial<ResourceProviderConfig> = getDefaultResourceConfig(axiosMock as any)
  const wrapper = ({ children }: PropsWithChildren<{}>) => (
    <ResourceProvider options={config}>{children}</ResourceProvider>
  )

  const {
    result: { current: fetch },
  } = renderHook(() => useFetchResource<void>('http://test/'), { wrapper })
  await act(() =>
    fetch({
      requestConfig: {
        url: 'http://peretest/',
      },
    })
  )
  expect(axiosMock).toBeCalledWith(expect.objectContaining({ url: 'http://peretest/' }))
})
Example #7
Source File: useAsync.test.ts    From advocacy-maps with MIT License 6 votes vote down vote up
test("useAsyncCallback waits for execute to update when the callback changes", async () => {
  const { result, waitFor, rerender } = renderHook(
    (cb: any) => useAsyncCallback(cb),
    {
      initialProps: callback1
    }
  )

  act(() => void result.current.execute())
  await waitFor(() => expect(result.current.result).toBe(1))

  rerender(callback2)
  expect(result.current.result).toBe(1)
  act(() => void result.current.execute())
  await waitFor(() => expect(result.current.result).toBe(2))
})
Example #8
Source File: Sidebar.spec.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
it('should remove filter alert if the user has filters and opened feed filters', async () => {
  let mutationCalled = false;
  mockGraphQL({
    request: {
      query: UPDATE_ALERTS,
      variables: { data: { filter: false } },
    },
    result: () => {
      mutationCalled = true;
      return { data: { _: true } };
    },
  });
  renderComponent({ filter: true });

  await act(async () => {
    const feedFilters = await screen.findByText('Feed filters');
    feedFilters.click();
  });

  await waitFor(() => {
    const key = getFeedSettingsQueryKey(defaultUser);
    const data = client.getQueryData(key) as AllTagCategoriesData;
    expect(getHasAnyFilter(data.feedSettings)).toBeTruthy();
  });

  expect(updateAlerts).toBeCalledWith({ filter: false });
  expect(mutationCalled).toBeTruthy();
});
Example #9
Source File: useMemo.test.ts    From use-memo-value with MIT License 6 votes vote down vote up
test("basics", t => {
	let { result } = renderHook(() => {
		let [rawValue, setRawValue] = useState({ name: "starting value" })
		let memoValue = useMemoValue(rawValue)
		return { rawValue, setRawValue, memoValue }
	})

	// init
	t.is(result.current.rawValue, result.current.memoValue)

	// update to same value
	act(() => result.current.setRawValue({ name: "starting value" }))
	t.not(result.current.rawValue, result.current.memoValue)
	t.is(result.current.memoValue.name, "starting value")

	// update to new value
	act(() => result.current.setRawValue({ name: "changed value" }))
	t.is(result.current.rawValue, result.current.memoValue)
	t.is(result.current.memoValue.name, "changed value")
})
Example #10
Source File: useDialog.test.ts    From baleen3 with Apache License 2.0 6 votes vote down vote up
test('open should open, close should close', () => {
  const { result } = renderHook(() => useDialog())
  expect(result.current[0]).toBe(false)

  act(() => {
    result.current[1]()
  })

  expect(result.current[0]).toBe(true)

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

  expect(result.current[0]).toBe(false)
})
Example #11
Source File: useControlledState.test.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
describe('useControlledState', () => {
  const newState = 'new';

  it('can not change with self', () => {
    const state = 'origin';
    const { result } = renderHook(() => useControlledState(state, ''));
    expect(result.current[0]).toBe(state);
    expect(typeof result.current[1]).toBe('function');

    act(() => {
      result.current[1](newState);
    });

    expect(result.current[0]).toBe(state);
  });

  it('will be changed by props', () => {
    let state = 'origin';
    const { result, rerender } = renderHook(() => useControlledState(state, ''));

    state = newState;
    rerender();

    expect(result.current[0]).toBe(state);
  });

  it('will be changed for undefined', () => {
    const { result } = renderHook(() => useControlledState<string | undefined>(undefined, undefined));
    act(() => {
      result.current[1](newState, true);
    });
    expect(result.current[0]).toBe(newState);
  });

  it('will use empty when is undefined', () => {
    const { result } = renderHook(() => useControlledState(undefined, ''));
    expect(result.current[0]).toBe('');
  });
});
Example #12
Source File: useWindowSize.test.ts    From usehooks-ts with MIT License 6 votes vote down vote up
describe('useElementSize()', () => {
  it('should initialize', () => {
    const { result } = setupHook()
    const { height, width } = result.current
    expect(typeof height).toBe('number')
    expect(typeof width).toBe('number')
  })

  it('should return the corresponding height', () => {
    const { result } = setupHook()

    act(() => {
      windowResize('height', 420)
    })
    expect(result.current.height).toBe(420)

    act(() => {
      windowResize('height', 2196)
    })

    expect(result.current.height).toBe(2196)
  })

  it('should return the corresponding width', () => {
    const { result } = setupHook()
    act(() => {
      windowResize('width', 420)
    })

    expect(result.current.width).toBe(420)

    act(() => {
      windowResize('width', 2196)
    })

    expect(result.current.width).toBe(2196)
  })
})
Example #13
Source File: useWindowSize.test.tsx    From chroma-react with MIT License 6 votes vote down vote up
describe('useWindowSize', () => {
  it('should be defined', () => {
    expect(useWindowSize).toBeDefined();
  });

  it('should update width', () => {
    const hook = renderHook(() => useWindowSize());
    act(() => {
      window.resizeTo(320, 768);
      hook.rerender();
    });
    expect(hook.result.current.width).toBe(320);
    act(() => {
      window.resizeTo(640, 768);
      hook.rerender();
    });
    expect(hook.result.current.width).toBe(640);
  });

  it('should update height', () => {
    const hook = renderHook(() => useWindowSize());
    act(() => {
      window.resizeTo(320, 500);
      hook.rerender();
    });
    expect(hook.result.current.height).toBe(500);
    act(() => {
      window.resizeTo(320, 1000);
      hook.rerender();
    });
    expect(hook.result.current.height).toBe(1000);
  });
});
Example #14
Source File: voter.test.ts    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
describe('testing VoterContainer', () => {
  test('data can be created', () => {
    const { result } = renderHook(
      () => VoterContainer.useContainer(),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      { wrapper: VoterContainer.Provider as any }
    )
    const uid = result.current.voter.uid
    expect(uid.length).toBeGreaterThan(5)

    // Assigning a new field updates it
    act(// eslint-disable-next-line @typescript-eslint/camelcase
      () => result.current.conservativeUpdateVoter({utmCampaign: 'c1'})
    )
    expect(result.current.voter.utmCampaign).toBe('c1')

    // Assigning again doesn't do anything
    act(// eslint-disable-next-line @typescript-eslint/camelcase
      () => result.current.conservativeUpdateVoter({utmCampaign: 'c2'})
    )
    expect(result.current.voter.utmCampaign).toBe('c1')

    // rerender does not trigger a new uid
    const { result: result2 } = renderHook(
      () => VoterContainer.useContainer(),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      { wrapper: VoterContainer.Provider as any }
    )
    const uid2 = result2.current.voter.uid
    expect(uid).toBe(uid2)
  })
})
Example #15
Source File: use-form.values.test.ts    From mantine with MIT License 6 votes vote down vote up
describe('@mantine/form/use-form values', () => {
  it('sets correct values based on initialValues', () => {
    const hook = renderHook(() =>
      useForm({
        initialValues: {
          orange: 'fruit',
          banana: true,
          apple: 20,
          grape: { nested: true },
        },
      })
    );

    expect(hook.result.current.values).toStrictEqual({
      orange: 'fruit',
      banana: true,
      apple: 20,
      grape: { nested: true },
    });
  });

  it('sets field value with setFieldValue handler', () => {
    const hook = renderHook(() => useForm({ initialValues: { orange: 'fruit', banana: true } }));

    act(() => hook.result.current.setFieldValue('banana', false));
    expect(hook.result.current.values).toStrictEqual({ orange: 'fruit', banana: false });

    act(() => hook.result.current.setFieldValue('orange', 'vegetable'));
    expect(hook.result.current.values).toStrictEqual({ orange: 'vegetable', banana: false });
  });

  it('sets fields values with setValues handler', () => {
    const hook = renderHook(() => useForm({ initialValues: { orange: 'fruit', banana: true } }));
    act(() => hook.result.current.setValues({ orange: 'vegetable', banana: false }));
    expect(hook.result.current.values).toStrictEqual({ orange: 'vegetable', banana: false });
  });
});
Example #16
Source File: useMouseDown.test.ts    From minesweeper with MIT License 6 votes vote down vote up
describe('useMousedown hook test', () => {
  it('Should toggle state after onMouseDown/onMouseUp calls', () => {
    const { result } = renderHook(useMouseDown);

    const [mousedown, onMouseDown, onMouseUp] = result.current;

    expect(mousedown).toBe(false);

    act(onMouseDown);
    expect(result.current[0]).toBe(true);

    act(onMouseUp);
    expect(result.current[0]).toBe(false);

    act(onMouseDown);
    expect(result.current[0]).toBe(true);
  });
});
Example #17
Source File: useCounter.test.ts    From react-js-tutorial with MIT License 6 votes vote down vote up
test("should reset counter to updated initial value", () => {
  const { result, rerender } = renderHook(
    ({ initialValue }) => useCounter(initialValue),
    {
      initialProps: { initialValue: 0 },
    }
  );
  expect(result.current.count).toBe(0);
  rerender({ initialValue: 10 });
  act(() => {
    result.current.reset();
  });
  expect(result.current.count).toBe(10);
});
Example #18
Source File: useDebounce.spec.ts    From kodiak-ui with MIT License 6 votes vote down vote up
describe('useDebounce', () => {
  const initialValue = 'initialValue'
  const updatedValue = 'updatedValue'
  const delay = 500

  it('should return initial value in first render', () => {
    const { result } = setUp({ value: initialValue, delay })
    expect(result.current).toBe(initialValue)
  })

  it('should return updated value after delay', () => {
    const { result, rerender } = setUp({ value: initialValue, delay })

    rerender({ value: updatedValue })
    expect(result.current).toBe(initialValue)

    act(() => jest.advanceTimersByTime(delay))

    expect(result.current).toBe(updatedValue)
  })

  it('should use new delay value', () => {
    const newDelay = 100
    const { result, rerender } = setUp({ value: initialValue, delay })

    rerender({ delay: newDelay, value: updatedValue })

    act(() => jest.advanceTimersByTime(newDelay))

    expect(result.current).toBe(updatedValue)
  })
})
Example #19
Source File: useLokiLabels.test.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
describe('useLokiLabels hook', () => {
  it('should refresh labels', async () => {
    const datasource = makeMockLokiDatasource({});
    const languageProvider = new LanguageProvider(datasource);
    const logLabelOptionsMock = ['Holy mock!'];
    const rangeMock: AbsoluteTimeRange = {
      from: 1560153109000,
      to: 1560153109000,
    };

    languageProvider.logLabelOptions = ['initial'];

    languageProvider.refreshLogLabels = () => {
      languageProvider.logLabelOptions = logLabelOptionsMock;
      return Promise.resolve();
    };

    const { result, waitForNextUpdate } = renderHook(() => useLokiLabels(languageProvider, true, rangeMock));
    expect(result.current.logLabelOptions).toEqual(['initial']);
    act(() => result.current.refreshLabels());
    await waitForNextUpdate();
    expect(result.current.logLabelOptions).toEqual(logLabelOptionsMock);
  });
});
Example #20
Source File: useSetCartUnsafe.test.ts    From gatsby-theme-shopify-manager with MIT License 6 votes vote down vote up
describe('useSetCartUnsafe()', () => {
  it('returns a function to set the cart in state', async () => {
    const localStorageSpy = jest.spyOn(LocalStorage, 'set');
    const {result} = await renderHookWithContext(() => useSetCartUnsafe());

    const newCart = {...Mocks.CART, id: 'my_new_cart'};
    act(() => {
      // @ts-ignore
      result.current(newCart);
    });

    expect(localStorageSpy).toHaveBeenCalledWith(
      LocalStorageKeys.CART,
      JSON.stringify(newCart),
    );
  });

  it('throws an error if a given variant Id is not found in the cart', async () => {
    const {result} = renderHook(() => useSetCartUnsafe());

    // @ts-ignore
    expect(() => result.current(Mocks.CART)).toThrow(
      'You forgot to wrap this in a Provider object',
    );
  });
});
Example #21
Source File: useFileReader.test.ts    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
describe('recipients list > useFileReader', () => {
  afterEach(() => cleanup());

  test('set parsed numbers correctly', async () => {
    await act(async () => {
      let { waitForNextUpdate } = renderHook(() =>
        useFileReader(selectedFile, setAlert, setParsedNumbers)
      );

      await waitForNextUpdate();

      await new Promise((r) => setTimeout(r, 200));

      expect(setParsedNumbers).toHaveBeenCalledWith([
        '+12025555555',
        '+12025555556',
        '+12025555557',
        '+12025555558',
      ]);
    });
  });
});
Example #22
Source File: store.clear.test.ts    From state-pool with MIT License 6 votes vote down vote up
test('should clear the entire global state and initialize `count` with 5', () => {
    const hook1 = renderHook(() => store.useState("count"))

    act(() => {
        hook1.result.current[1](count => 1)
    })

    act(() => {
        store.clear(()=>{ store.setState("count", 5); })
    })

    expect(hook1.result.current[0]).toStrictEqual(5)
})
Example #23
Source File: actions.test.ts    From use-selected-items-hook with MIT License 5 votes vote down vote up
describe("Hook Actions", () => {
  it("should toggle a single item", () => {
    const { result } = renderHook(() => useSelectedItems<TestItem>({
      itemIdentifierKey: "id",
      initialItems: INITIAL_TEST_ITEMS,
    }));

    const item = INITIAL_TEST_ITEMS[0];

    act(() => result.current.toggleSingleItem(item));

    expect(result.current.selectedItems).toEqual([item]);

    act(() => result.current.toggleSingleItem(item));

    expect(result.current.selectedItems).toEqual([]);
  });

  it("should toggle all items", () => {
    const { result } = renderHook(() => useSelectedItems<TestItem>({
      itemIdentifierKey: "id",
      initialItems: INITIAL_TEST_ITEMS,
    }));

    act(() => result.current.toggleAllItems());

    expect(result.current.selectedItems).toEqual(INITIAL_TEST_ITEMS);

    act(() => result.current.toggleAllItems());

    expect(result.current.selectedItems).not.toEqual(INITIAL_TEST_ITEMS);
    expect(result.current.selectedItems).toHaveLength(0);
  });

  it("should throw error for invalid item identifier key", () => {
    const { result } = renderHook(() => useSelectedItems<TestItem>({
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
      itemIdentifierKey: "invalid-key",
      initialItems: INITIAL_TEST_ITEMS,
    }));

    expect(result.error).toEqual(Error(ERROR_MESSAGES.INVALID_ITEM_IDENTIFIER));
  });
});
Example #24
Source File: login.hooks.spec.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
describe('useLogin specs', () => {
  it('should return an object: credential with default values and setCredential a function when it calls it', () => {
    // Arrange

    // Act
    const { result } = renderHook(() => useLogin());

    // Assert
    const defaultCredential: Credential = { name: '', password: '' };
    expect(result.current.credential).toEqual(defaultCredential);
    expect(result.current.setCredential).toEqual(expect.any(Function));
  });

  it('should update credential when it calls setCredential', () => {
    // Arrange
    const newCredential: Credential = { name: 'admin', password: 'test' };

    // Act
    const { result } = renderHook(() => useLogin());

    act(() => {
      result.current.setCredential(newCredential);
    });

    // Assert
    expect(result.current.credential).toEqual(newCredential);
  });

  it('should return user equals null and onLogin function', () => {
    // Arrange

    // Act
    const { result } = renderHook(() => useLogin());

    // Assert
    expect(result.current.user).toBeNull();
    expect(result.current.setCredential).toEqual(expect.any(Function));
  });

  it('should update user when it send valid credentials using onLogin', async () => {
    // Arrange
    const adminUser: User = { email: '[email protected]', role: 'admin' };
    const loginStub = jest.spyOn(api, 'login').mockResolvedValue(adminUser);

    // Act
    const { result, waitForNextUpdate } = renderHook(() => useLogin());

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

    await waitForNextUpdate();

    // Assert
    expect(loginStub).toHaveBeenCalled();
    expect(result.current.user).toEqual(adminUser);
  });
});
Example #25
Source File: params.test.ts    From useTable with MIT License 5 votes vote down vote up
describe('useTable#getParams', () => {
  it('default', async () => {
    const dataSource = [{ name: 'ahooks' }];
    const TOTAL = 25;
    const { result, waitForNextUpdate } = renderHook(() =>
      useTable(() => {
        return service({ dataSource, total: TOTAL });
      })
    );

    await waitForNextUpdate();
    await waitForNextUpdate();
    expect(result.current.getParams()).toEqual({ current: 1, pageSize: 20 });

    const { onChange } = result.current.paginationProps;
    act(() => {
      onChange(2);
    });

    await waitForNextUpdate();
    await waitForNextUpdate();
    expect(result.current.getParams()).toEqual({ current: 2, pageSize: 20 });

    const { onPageSizeChange } = result.current.paginationProps;
    act(() => {
      onPageSizeChange(10);
    });

    await waitForNextUpdate();
    await waitForNextUpdate();
    expect(result.current.getParams()).toEqual({ current: 1, pageSize: 10 });

    act(() => {
      result.current.query({ name: 'test' });
    });

    await waitForNextUpdate();
    await waitForNextUpdate();
    expect(result.current.getParams()).toEqual({ name: 'test', current: 1, pageSize: 10 });

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

    await waitForNextUpdate();
    await waitForNextUpdate();
    expect(result.current.getParams()).toEqual({ current: 1, pageSize: 10 });
  });
});
Example #26
Source File: useEvents-spec.ts    From S2 with MIT License 5 votes vote down vote up
describe('useEvents tests', () => {
  let s2: SpreadSheet;

  beforeEach(() => {
    s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options);

    const mockCell = createMockCellInfo('test', { rowIndex: 0, colIndex: 0 });

    s2.getCell = () => mockCell.mockCell;
    s2.render();
  });

  test('useEvents should be defined', () => {
    const mockBaseSheetProps: SheetComponentsProps = {
      dataCfg: undefined,
      options: undefined,
      spreadsheet: () => s2,
    };
    const { result } = renderHook(() => useEvents(mockBaseSheetProps, s2));
    expect(result.current).toBeUndefined();
  });

  test.each(
    cellEventCases.concat(S2EventCases as any) as Array<{
      event: S2Event;
      name: keyof SheetComponentsProps;
      eventHook: typeof useCellEvent | typeof useS2Event;
    }>,
  )('eventHook should be called with %s', ({ event, name, eventHook }) => {
    const props: SheetComponentsProps = {
      dataCfg: mockDataConfig,
      options: s2Options,
      [name]: jest.fn(),
    };

    const { rerender, unmount } = renderHook(
      ({ props }) => eventHook(event, props[name] as any, s2),
      {
        initialProps: { props },
      },
    );

    const MockEmitFn = () => {
      s2.emit(event, {
        target: {
          get: () => {},
        },
        stopPropagation: () => {},
      } as unknown as GEvent);
    };
    // emit
    act(MockEmitFn);
    expect(props[name]).toBeCalledTimes(1);

    // cleanup effects for useEffect hooks
    unmount();
    // emit
    act(MockEmitFn);
    expect(props[name]).toBeCalledTimes(1);

    const newProps = {
      ...props,
      [name]: jest.fn(),
    };
    rerender({ props: newProps });
    expect(newProps[name]).toBeCalledTimes(0);
  });
});
Example #27
Source File: useCreateReleaseCandidate.test.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
describe('useCreateReleaseCandidate', () => {
  beforeEach(jest.clearAllMocks);

  it('should return the expected responseSteps and progress', async () => {
    const { result } = renderHook(() =>
      useCreateReleaseCandidate({
        defaultBranch: mockDefaultBranch,
        latestRelease: mockReleaseVersionCalver,
        releaseCandidateGitInfo: mockNextGitInfoCalver,
        project: mockCalverProject,
      }),
    );

    await act(async () => {
      await waitFor(() => result.current.run());
    });

    expect(result.error).toEqual(undefined);
    expect(result.current.responseSteps).toHaveLength(6);
  });

  it('should return the expected responseSteps and progress (with onSuccess)', async () => {
    const { result } = renderHook(() =>
      useCreateReleaseCandidate({
        defaultBranch: mockDefaultBranch,
        latestRelease: mockReleaseVersionCalver,
        releaseCandidateGitInfo: mockNextGitInfoCalver,
        project: mockCalverProject,
        onSuccess: jest.fn(),
      }),
    );

    await act(async () => {
      await waitFor(() => result.current.run());
    });

    expect(result.current.responseSteps).toHaveLength(7);
    expect(result.current).toMatchInlineSnapshot(`
      Object {
        "progress": 100,
        "responseSteps": Array [
          Object {
            "link": "https://latestCommit.html_url",
            "message": "Fetched latest commit from \\"mock_defaultBranch\\"",
            "secondaryMessage": "with message \\"latestCommit.commit.message\\"",
          },
          Object {
            "message": "Created Release Branch",
            "secondaryMessage": "with ref \\"mock_createRef_ref\\"",
          },
          Object {
            "message": "Created Tag Object",
            "secondaryMessage": "with sha \\"mock_tag_object_sha\\"",
          },
          Object {
            "message": "Cut Tag Reference",
            "secondaryMessage": "with ref \\"mock_createRef_ref\\"",
          },
          Object {
            "link": "https://mock_compareCommits_html_url",
            "message": "Fetched commit comparison",
            "secondaryMessage": "rc/2020.01.01_1...rc/2020.01.01_1",
          },
          Object {
            "link": "https://mock_createRelease_html_url",
            "message": "Created Release Candidate \\"mock_createRelease_name\\"",
            "secondaryMessage": "with tag \\"rc-2020.01.01_1\\"",
          },
          Object {
            "icon": "success",
            "message": "Success callback successfully called ?",
          },
        ],
        "run": [Function],
        "runInvoked": true,
      }
    `);
  });
});
Example #28
Source File: Params.test.tsx    From ke with MIT License 5 votes vote down vote up
describe.each([
  ['useListFilters', useListFilters, 'filters', filtersArbitrary],
  ['useListOrder', useListOrder, 'orderBy', orderArbitrary],
  ['useListPagination', useListPagination, 'pagination', paginationArbitrary],
] as TestTuple<unknown>[])('%s', (_, hook, paramsKey, valueArbitrary) => {
  it('Get valid value from context', () => {
    fc.assert(
      fc.property(paramsArbitrary, (params) => {
        const wrapper = ({ children }: PropsWithChildren<{}>): JSX.Element => (
          <ListParamsProvider value={params} onChange={jest.fn()}>
            {children}
          </ListParamsProvider>
        )

        const { result } = renderHook(() => hook(), { wrapper })

        expect(result.current[0]).toBe(params[paramsKey])
      })
    )
  })

  it('Get correct updater from context', () => {
    fc.assert(
      fc.property(paramsArbitrary, valueArbitrary, (params, changed) => {
        const handleChangeSpy = jest.fn<void, [unknown]>()
        const wrapper = ({ children }: PropsWithChildren<{}>): JSX.Element => (
          <ListParamsProvider value={params} onChange={handleChangeSpy}>
            {children}
          </ListParamsProvider>
        )

        const { result } = renderHook(() => hook(), { wrapper })
        act(() => {
          result.current[1](changed)
        })

        expect(handleChangeSpy).toBeCalledTimes(1)
        expect(handleChangeSpy.mock.calls[0][0]).toEqual({ ...params, [paramsKey]: changed })
      })
    )
  })
})
Example #29
Source File: bills.test.ts    From advocacy-maps with MIT License 5 votes vote down vote up
async function renderWithSort(sort: any) {
  const { waitFor, result } = renderHook(() => useBills())
  act(() => void result.current.setSort(sort))
  await waitFor(() => expect(result.current.items.loading).toBeFalsy())

  return result.current.items.result!
}