react-dom/test-utils#act TypeScript Examples
The following examples show how to use
react-dom/test-utils#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: BuildingCard.test.tsx From zapquaker with MIT License | 6 votes |
it("should show message if building cannot be destroyed", () => {
act(() => {
render(
<BuildingCard
zapLevel={1}
quakeLevel={1}
spellCapacity={1}
building={building}
/>,
container
);
});
const span = container.querySelector(".no-combination");
expect(span?.textContent).toBeDefined();
});
Example #2
Source File: DateField.tsx From uniforms-patternfly with Apache License 2.0 | 6 votes |
test('<DateField> - renders a input which correctly reacts on change (DatePicker)', () => {
const onChange = jest.fn();
const now = '2000-04-04';
const element = <DateField name="x" />;
const wrapper = mount(
element,
createContext({ x: { type: Date } }, { onChange })
);
act(() => {
wrapper.find('DatePicker').find('input').prop('onChange')!({
currentTarget: { value: now },
} as any);
});
expect(onChange).toHaveBeenLastCalledWith('x', new Date(`${now}T00:00:00Z`));
});
Example #3
Source File: Login.test.tsx From ts-redux-react-realworld-example-app with MIT License | 6 votes |
it('Should have email and password values from store', async () => {
await act(async () => {
await render(<Login />);
});
await act(async () => {
store.dispatch(updateField({ name: 'email', value: '1234' }));
store.dispatch(updateField({ name: 'password', value: '5678' }));
});
expect(screen.getByPlaceholderText('Email')).toHaveValue('1234');
expect(screen.getByPlaceholderText('Password')).toHaveValue('5678');
});
Example #4
Source File: issue-522-spec.tsx From S2 with MIT License | 6 votes |
describe('spreadsheet normal spec', () => {
act(() => {
ReactDOM.render(<MainLayout />, getContainer());
});
test(`sampleForAllLevels shouldn't include total node`, () => {
const { sampleNodesForAllLevels } =
sheetInstance.facet.layoutResult.rowsHierarchy;
expect(sampleNodesForAllLevels).toHaveLength(3);
expect(sampleNodesForAllLevels).toSatisfyAll(
(node: Node) => !node.isTotals,
);
});
});
Example #5
Source File: sourceQueryDebugModal.test.ts From sdc-ide with MIT License | 6 votes |
test('onSave', async () => {
await setup();
const { result, waitFor } = renderHook(() => useSourceQueryDebugModal(props));
await waitFor(() => isSuccess(result.current.bundleResultRD));
await act(() => result.current.onSave(resourceSuccess));
const responseMustBeSuccess = await updateQuestionnaire(resourceSuccess as any, false);
expect(isSuccess(responseMustBeSuccess)).toBeTruthy();
await act(() => result.current.onSave(resourceFailure));
const responseMustBeFailure = await updateQuestionnaire(resourceFailure as any, false);
expect(isFailure(responseMustBeFailure)).toBeTruthy();
});
Example #6
Source File: DateTimeRangeListWidget.test.tsx From ke with MIT License | 6 votes |
test('DateTimeRangeListWidget properly handle event', () => {
const component = mount(getComponent())
act(() => {
component.find(BaseDateTimeRangeWidget).first().props().handleChangeDate(new Date('2021-02-02T00:00:00'), 'end', 0)
})
expect(submitChangeMock).toHaveBeenCalledWith({
url: 'https://some-test-target.com',
payload: { testPayload: [['2021-01-01T00:00:00', '2021-02-02T00:00:00']] },
})
})
Example #7
Source File: ens.test.tsx From safe-airdrop with MIT License | 6 votes |
test("isEnsEnabled with ens capable network", async () => {
const fakeWeb3Provider: any = {
getNetwork: () => {
return Promise.resolve({ chainId: 4, network: "rinkeby", ensAddress: "0x00000000000001" });
},
};
jest.spyOn(ethers.providers, "Web3Provider").mockImplementation(() => fakeWeb3Provider);
let renderedContainer: undefined | RenderResult;
act(() => {
if (container !== null) {
renderedContainer = renderTestComponent(container);
}
});
sendSafeInfo();
expect(renderedContainer).toBeTruthy();
const ensEnabledElement = await screen.findByTestId("isEnsEnabled");
expect(ensEnabledElement?.innerHTML).toBe("true");
});
Example #8
Source File: utils.tsx From yforms with MIT License | 6 votes |
export async function waitForComponentToPaint<P = any>(wrapper: ReactWrapper<P>, amount = 0) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, amount));
wrapper.update();
});
}
Example #9
Source File: ReceiveModal.test.tsx From raspiblitz-web with MIT License | 6 votes |
describe("ReceiveModal", () => {
test("Retrieves new on-chain address on click of on-chain button", async () => {
const { container } = render(
<I18nextProvider i18n={i18n}>
<ReceiveModal onClose={() => {}} />
</I18nextProvider>
);
await act(async () => {
(await screen.findByText("wallet.on_chain")).click();
});
await waitFor(() => expect(container.querySelector("svg")).toBeDefined());
});
});
Example #10
Source File: Toast.spec.tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
it('should display a toast notification', async () => {
renderComponent();
const button = await screen.findByText('Regular Toast');
fireEvent.click(button);
await screen.findByRole('alert');
await screen.findByText('Sample Notification');
await act(() => new Promise((resolve) => setTimeout(resolve, 1500))); // wait for the toast to expire
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
Example #11
Source File: LaunchpadWrapper.spec.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
describe("LaunchpadWrapper", () => {
it("should fade out when launchpad will close", async () => {
const handleWillClose = jest.fn();
const handleClose = jest.fn();
const wrapper = mount(
<LaunchpadWrapper onWillClose={handleWillClose} onClose={handleClose} />
);
act(() => {
wrapper.find(Launchpad).invoke("onWillClose")();
});
wrapper.update();
expect(wrapper.find(CSSTransition).prop("in")).toBe(false);
expect(handleWillClose).toBeCalled();
expect(handleClose).not.toBeCalled();
await jest.advanceTimersByTime(wrapper
.find(CSSTransition)
.prop("timeout") as number);
expect(handleClose).toBeCalled();
});
});
Example #12
Source File: useProvider.spec.tsx From next-core with GNU General Public License v3.0 | 6 votes |
describe("useProviderHook with React Suspense", () => {
it("should work with React Suspense", async () => {
const ToDo = () => {
const { error } = useProvider(
"easyops.custom_api@test",
{ suspense: true },
[]
);
return <div>{error ? "error" : "rendered"}</div>;
};
// eslint-disable-next-line react/display-name
const TestComponent = () => {
return (
<div>
<Suspense fallback={"loading..."}>
<ToDo />
</Suspense>
</div>
);
};
const wrapper = mount(<TestComponent />);
expect(wrapper.find("Suspense").prop("fallback")).toBe("loading...");
await act(async () => {
await (global as any).flushPromises();
});
expect(wrapper.find("ToDo").text()).toBe("rendered");
});
});
Example #13
Source File: index.test.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
describe('BackToTop', () => {
Element.prototype.scrollTo = function (opt?: ScrollToOptions | number) {
if (typeof opt !== 'number') {
const { top, left } = opt as ScrollToOptions;
this.scrollTop = top || 0;
this.scrollLeft = left || 0;
}
};
it('should back to top', async () => {
document.body.innerHTML = '<div id="main" style="height: 400px; overflow-y: auto"></div>';
const div = document.getElementById('main') as HTMLDivElement;
const scrollToSpy = jest.spyOn(window, 'scrollTo').mockImplementation((x: number, y: number) => {
div.scrollLeft = x;
div.scrollTop = y;
});
act(() => {
render(
<div id="child" style={{ height: '1000px' }}>
<BackToTop />
</div>,
div,
);
});
window.scrollTo(0, 500);
expect(div.scrollTop).toBe(500);
act(() => {
div.dispatchEvent(new Event('scroll'));
});
const button = document.querySelector('.scroll-top-btn') as Element;
act(() => {
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(div.scrollTop).toBe(0);
scrollToSpy.mockRestore();
unmountComponentAtNode(div);
});
});
Example #14
Source File: AppBar.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('selects the matching nav-tab', async () => {
const { getByText } = render(
<MemoryRouter initialEntries={['/bar']}>
<AppBar
routes={[
{
label: 'foo',
path: '/foo',
showInNav: true,
component: React.Fragment,
exact: false,
},
{
label: 'bar',
path: '/bar',
showInNav: true,
component: React.Fragment,
exact: false,
},
]}
/>
</MemoryRouter>
);
await act(() => delay(300)); // Wait for tab indicator async DOM updates.
expect(isTabActive(getByText('foo'))).toBe(false);
expect(isTabActive(getByText('bar'))).toBe(true);
});
Example #15
Source File: utils.ts From geist-ui with MIT License | 6 votes |
updateWrapper = async (wrapper: ReactWrapper, time: number = 0) => {
await act(async () => {
await sleep(time)
wrapper.update()
})
}
Example #16
Source File: Console.test.tsx From devtools-ds with MIT License | 6 votes |
function enterText(input: HTMLElement, value: string) {
act(() => {
fireEvent.change(input, { target: { value } });
});
act(() => {
fireEvent.keyDown(input, { key: "Enter" });
});
}
Example #17
Source File: SpellLevel.test.tsx From zapquaker with MIT License | 5 votes |
it("displays correct level", () => {
act(() => {
ReactDOM.render(<SpellLevel level={5} maxLevel={6}/>, container);
});
const a = container.querySelector(".level-container");
expect(a?.textContent).toBe("5");
});
Example #18
Source File: useHotkeys.test.tsx From jmix-frontend with Apache License 2.0 | 5 votes |
describe('useHotkeys()', () => {
it('correctly add hotkeyConfig', () => {
const {result, unmount, rerender} = renderHook(() => {
useHotkey(oneHotkeyConfig, () => undefined);
return useHotkeyStore();
}, {
wrapper,
initialProps: {
hotkeyStore: new HotkeyStore([]),
}
});
expect(result.current.hotkeyConfigs).toEqual([oneHotkeyConfig]);
rerender();
expect(result.current.hotkeyConfigs).toEqual([oneHotkeyConfig]);
unmount();
expect(result.current.hotkeyConfigs).toEqual([]);
});
it('keyboard listener works on the document', async () => {
const spy = jest.fn();
renderHook(() => useHotkey(oneHotkeyConfig, spy), {
wrapper,
initialProps: {
hotkeyStore: new HotkeyStore([]),
}
});
act(() => {
document.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 191}));
});
expect(spy).toHaveBeenCalledTimes(1);
});
it('callback is called correctly on component stages', async () => {
const spy = jest.fn();
const {rerender, unmount} = renderHook(() => useHotkey(oneHotkeyConfig, spy), {
wrapper,
initialProps: {
hotkeyStore: new HotkeyStore([]),
}
});
act(() => {
document.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 191}));
});
expect(spy).toHaveBeenCalledTimes(1);
rerender();
act(() => {
document.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 191}));
});
expect(spy).toHaveBeenCalledTimes(2);
unmount();
act(() => {
document.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 191}));
});
expect(spy).toHaveBeenCalledTimes(2);
});
});
Example #19
Source File: issue-594-spec.tsx From S2 with MIT License | 5 votes |
describe('SheetComponent Ref Tests', () => {
beforeEach(() => {
s2 = null;
mockRef.current = null;
});
test('should get spreadsheet instance by', () => {
act(() => {
ReactDOM.render(<MainLayout sheetType="pivot" />, getContainer());
});
expect(s2).toBeInstanceOf(SpreadSheet);
expect(mockRef.current).toBeInstanceOf(SpreadSheet);
});
test('should get table spreadsheet instance', () => {
act(() => {
ReactDOM.render(<MainLayout sheetType="table" />, getContainer());
});
expect(s2).toBeInstanceOf(TableSheet);
expect(mockRef.current).toBeInstanceOf(TableSheet);
});
test('should register events when sheet type updated', () => {
act(() => {
ReactDOM.render(
<MainLayout sheetType="pivot" toggleSheetType />,
getContainer(),
);
});
// toggle sheet type
act(() => {
document.querySelector('.btn').dispatchEvent(new Event('click'));
});
// should don't miss events
expect(s2.getEvents()[S2Event.DATA_CELL_TREND_ICON_CLICK]).toBeDefined();
expect(mockRef.current.getEvents()[S2Event.COL_CELL_CLICK]).toBeDefined();
});
});