@testing-library/react#waitFor JavaScript Examples
The following examples show how to use
@testing-library/react#waitFor.
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: testutils.js From karto with MIT License | 7 votes |
export function waitForItemPositionStable(item, timeout) {
let previousPosition = null;
return waitFor(() => {
let isStable = false;
const currentPosition = getItemPosition(item);
if (currentPosition != null) {
if (previousPosition != null) {
isStable = Math.abs(previousPosition.clientX - currentPosition.clientX) < 0.1
&& Math.abs(previousPosition.clientY - currentPosition.clientY) < 0.1;
}
previousPosition = currentPosition;
}
return new Promise((resolve, reject) => isStable ? resolve() : setTimeout(reject, 200));
}, { timeout });
}
Example #2
Source File: index.jsdom.test.jsx From apps-todo-list with MIT License | 6 votes |
async function openAsync(table, view, field) {
act(() => {
const input = screen.getByLabelText('Table');
const option = screen.getByText(table);
userEvent.selectOptions(input, [option]);
});
act(() => {
const input = screen.getByLabelText('View');
const option = screen.getByText(view);
userEvent.selectOptions(input, [option]);
});
act(() => {
const input = screen.getByLabelText('Field');
const option = screen.getByText(field);
userEvent.selectOptions(input, [option]);
});
return waitFor(() => screen.getByRole('button', {name: 'Add'}));
}
Example #3
Source File: searchlist.test.js From healthcare-api-dicom-viewer with Apache License 2.0 | 6 votes |
test('Typing in search bar filters items', async () => {
const items = generateItems(60);
render(
<SearchList items={items} onClickItem={() => {}} isLoading={false}/>,
);
// Searching for item10 should filter to only one item
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item10'}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(1), {timeout: 2000});
// Searching for item6 should filter to two items (item6 and item60)
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item6'}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(2), {timeout: 2000});
// Searching for blank space should return all items (only 50 will be
// displayed as that is the initial max number of items until scroll)
fireEvent.input(screen.getByRole('textbox'), {target: {value: ' '}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(50), {timeout: 2000});
// Searching for item70 should yield no items
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item70'}});
await waitFor(() =>
expect(screen.queryAllByText('item', {exact: false})).toHaveLength(0), {timeout: 2000});
}, 20000);
Example #4
Source File: Crisp.test.jsx From react-crisp with Apache License 2.0 | 6 votes |
test('Crisp with a token ID', async () => {
const tokenId = 'foo-token-id';
await render(
<Crisp
crispWebsiteId="foo-website-id-token-id"
crispTokenId={tokenId}
/>,
);
await waitFor(() => expect(global.CRISP_TOKEN_ID).toMatch(/foo-token-id/));
});
Example #5
Source File: TasksTabs.tests.js From tasks-frontend with Apache License 2.0 | 6 votes |
describe('TasksTabs', () => {
let props;
beforeEach(() => {
props = {
className: 'tabs-background',
tabIndex: 0,
tabsList: TASKS_PAGE_TABS,
updateTab: jest.fn(),
};
});
afterEach(() => {
jest.clearAllMocks();
});
it('should render correctly', () => {
const { asFragment } = render(<TasksTabs {...props} />);
expect(asFragment()).toMatchSnapshot();
});
it('should update tab index', async () => {
render(<TasksTabs {...props} />);
userEvent.click(screen.getByText('Completed tasks'));
await waitFor(() =>
expect(props.updateTab).toHaveBeenCalledWith(expect.anything(), 1)
);
});
});
Example #6
Source File: basic.js From next-localization with MIT License | 6 votes |
test('Should be able to change locale', async () => {
const i18nInstance = I18n({
en: { hello: 'Hello, world!' }
});
function Root() {
return (
<I18nProvider i18nInstance={i18nInstance} locale={i18nInstance.locale()}>
<Child />
</I18nProvider>
);
}
function Child() {
const i18n = useI18n();
useEffect(() => {
i18n.set('de', { hello: 'Hello, Welt!' });
i18n.locale('de');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <p>{i18n.t('hello')}</p>;
}
const { getByText } = render(<Root />);
await waitFor(() => {
expect(i18nInstance.locale()).toEqual('de');
expect(i18nInstance.table('en')).toEqual({ hello: 'Hello, world!' });
expect(i18nInstance.table('de')).toEqual({ hello: 'Hello, Welt!' });
expect(getByText('Hello, Welt!')).toBeInTheDocument();
});
});
Example #7
Source File: PortField.test.jsx From sgmr-service with MIT License | 6 votes |
describe('PortField', () => {
beforeEach(() => {
render(<PortField />);
});
it('should allow user to enter a location in a free text field if they click cannot find location in list', async () => {
expect(screen.getByTestId('portOther')).not.toBeVisible();
await waitFor(() => fireEvent.click(screen.getByText('I cannot find the location in the list')));
expect(screen.getByTestId('portOther')).toBeVisible();
expect(screen.getByTestId('portOtherInput')).toBeVisible();
fireEvent.change(screen.getByTestId('portOtherInput'), { target: { value: 'TEST' } });
expect(screen.getByTestId('portOtherInput').value).toBe('TEST');
});
it('should mirror the input of the the free text field on the combobox input when the free text field input changed', async () => {
expect(screen.getByTestId('portOther')).not.toBeVisible();
fireEvent.change(screen.getByTestId('portInput'), { target: { value: 'OTHER_VALUE' } });
await waitFor(() => fireEvent.click(screen.getByText('I cannot find the location in the list')));
fireEvent.change(screen.getByTestId('portOtherInput'), { target: { value: 'TEST' } });
expect(screen.getByTestId('portInput').value).toBe('TEST');
});
});
Example #8
Source File: search.test.js From maps with MIT License | 6 votes |
test('test if "loading" message appears after submitting a search', async () => {
render(<Search />)
screen.getByRole('textbox', { name: 'Name' });
userEvent.type(screen.getByRole('textbox', { name: 'Name' }), '1335 ASTOR');
userEvent.click(screen.getByRole('button', {name: /Submit/i}));
await waitFor(() => screen.findByText(/Loading/i));
expect(screen.getByText(/Loading.../i)).toHaveTextContent('Loading...');
})
Example #9
Source File: AppCalendar.test.js From ReactCookbook-source with MIT License | 6 votes |
describe('AppCalendar', () => {
beforeEach(() => {
renders = [];
t.next();
});
afterEach(() => {
console.log('Time taken: ', t.next().value);
console.table(renders);
});
it('should do stuff', async () => {
render(<App onRender={tracker}/>);
user.click(screen.getByRole('button', {name: /previous/i}))
await waitFor(() => {
return expect(screen.getByText(/year: 2022/i)).toBeInTheDocument();
}, {timeout: 5000});
}, 30000);
});
Example #10
Source File: IndexesHandler.test.jsx From covid with GNU General Public License v3.0 | 6 votes |
test('renders properly when rendered inside the multi-provider', async () => {
// Discard some logs
await catchConsoleLog(async () => {
const rendered = render(
<Provider>
<IndexesHandler>
<span role='child' />
</IndexesHandler>
</Provider>
)
// Initially show a Loading component
const loading = rendered.getByRole('loading')
expect(loading).toBeInTheDocument()
// Then the child component
await waitFor(() => {
const child = rendered.getByRole('child')
expect(child).toBeInTheDocument()
})
// TODO: Test clearing side effects
rendered.unmount()
})
})
Example #11
Source File: App.test.js From jsonmatic with MIT License | 6 votes |
test('Paste CSV displays table correctly', async () => {
let csv = [
['key', 'road', 'coord.lat', 'coord.lng', 'elem'],
['1', 'C-58', 42.02, 2.82, '?'],
['2', 'C-32', 41.35, 2.09, '?'],
['3', 'B-20', 41.44, 2.18, '?']
].map(e => e.join(`\t`)).join(`\n`);
Object.assign(navigator, {
clipboard: {
readText: () => csv
}
});
await render(<App />);
fireEvent.click(screen.getByDisplayValue('key'));
await waitFor(() => expect(document.getElementById('00')).toHaveClass('Selected'));
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: "v",
ctrlKey: true,
bubbles: true,
metaKey: true
})
);
await waitFor(() => expect(screen.getByDisplayValue('C-58')).toBeInTheDocument());
});
Example #12
Source File: ProjectSearchBox.test.jsx From ui with MIT License | 6 votes |
describe('ProjectSearchBox', () => {
it('Renders properly without inputs', () => {
render(
<ProjectSearchBox />,
);
// Expect component to contain input
expect(screen.getByPlaceholderText(/Filter by project/)).toBeInTheDocument();
});
it('Fires onchange when typed in', async () => {
const filterText = 'M musculus';
render(
<ProjectSearchBox onChange={onChangeSpy} />,
);
// Input value into search box
const input = screen.getByPlaceholderText(/Filter by project/);
userEvent.type(input, filterText);
// Expect onChange spy to be fired
await waitFor(() => {
expect(input.value).toBe(filterText);
expect(onChangeSpy).toHaveBeenCalled();
});
});
});
Example #13
Source File: my-profile.test.js From what-front with MIT License | 6 votes |
describe('My Profile', () => {
it('should render component', () => {
const { container } = render(
<Router>
<MyProfile />
</Router>
);
const profileContainer = container.getElementsByClassName('container');
expect(profileContainer).toMatchSnapshot();
});
it('should navigate to change password page', async () => {
const history = useHistory();
const { getByRole } = render(
<Router>
<MyProfile />
</Router>
);
const changePasswordButton = getByRole('button');
await waitFor(() => {
fireEvent.click(changePasswordButton);
});
expect(history.push).toHaveBeenCalledWith(paths.CHANGE_PASSWORD);
});
});
Example #14
Source File: interactions-helper.js From monday-ui-react-core with MIT License | 6 votes |
waitForElementVisible = getterFunc => {
return new Promise(resolve => {
let element;
waitFor(async () => {
element = await getterFunc();
expect(element).toBeVisible();
}).then(() => {
resolve(element);
});
});
}
Example #15
Source File: checkout-form.js From muffinsplantshop with BSD Zero Clause License | 6 votes |
test('Updates current section and values when submitting valid data with ShippingForm', async () => {
const setValues = jest.fn();
const setSection = jest.fn();
render(<ShippingForm
setValues={setValues}
setSection={setSection}
shippingValues={shippingValues} />);
fireEvent.click(screen.getByTestId("submit-shipping-button"));
await waitFor(() => {
expect(setSection).toHaveBeenCalledWith('billing');
expect(setValues).toHaveBeenCalledWith(shippingValues);
});
})
Example #16
Source File: Menu.test.js From react-menu with MIT License | 6 votes |
test.each([false, true])(
'Menu is unmounted before opening and closes after losing focus (portal = %s)',
async (portal) => {
utils.renderMenu({ portal });
// menu is unmounted
utils.expectButtonToBeExpanded(false);
utils.expectMenuToBeInTheDocument(false);
expect(queryByRole('menuitem')).not.toBeInTheDocument();
// Click the menu button, menu is expected to mount and open, and get focus
utils.clickMenuButton();
utils.expectButtonToBeExpanded(true);
utils.expectMenuToHaveState('opening', false);
utils.expectMenuToBeOpen(true);
expect(utils.queryMenu()).toHaveAttribute('aria-label', 'Open');
await waitFor(() => utils.expectMenuToHaveFocus());
const menuItems = queryAllByRole('menuitem');
expect(menuItems).toHaveLength(3);
menuItems.forEach((item) => utils.expectMenuItemToBeHover(item, false));
// focus something outside menu, expecting menu to close but keep mounted
act(() => queryByRole('button').focus());
utils.expectButtonToBeExpanded(false);
utils.expectMenuToHaveState('closing', false);
utils.expectMenuToBeOpen(false);
}
);
Example #17
Source File: LanguagePicker.test.js From transifex-javascript with Apache License 2.0 | 6 votes |
test('change language', async () => {
// Start mocking
const args = [];
const oldSetCurrentLocale = tx.setCurrentLocale;
tx.setCurrentLocale = function setCurrentLocaleMock(code) {
args.push(code);
};
render(<LanguagePicker />);
await waitFor(() => screen.getByText('Greek'));
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'el' } });
expect(args).toEqual(['el']);
// Reset mocking
tx.setCurrentLocale = oldSetCurrentLocale;
});
Example #18
Source File: main.test.js From healthcare-api-dicom-viewer with Apache License 2.0 | 5 votes |
// eslint-disable-next-line max-len
test('User can navigate between project, location, dataset, dicomStore, study, and series', async () => {
render(
<Main/>,
);
// Navigate through: project2 -> location5 -> dataset3 ->
// dicomStore4 -> study1 -> series1
// Ensure project1 through project5 are displayed
await waitFor(() =>
expect(screen.getAllByText(/^project\d+$/)).toHaveLength(5));
fireEvent.click(screen.getByText('project2'));
// Ensure location1 through location5 are displayed
await waitFor(() =>
expect(screen.getAllByText(/^location\d+$/)).toHaveLength(5));
fireEvent.click(screen.getByText('location5'));
// Ensure dataset1 through dataset5 are displayed
await waitFor(() =>
expect(screen.getAllByText(/^dataset\d+$/)).toHaveLength(5));
fireEvent.click(screen.getByText('dataset3'));
// Ensure dicomStore1 through dicomStore5 are displayed
await waitFor(() =>
expect(screen.getAllByText(/^dicomStore\d+$/)).toHaveLength(5));
fireEvent.click(screen.getByText('dicomStore4'));
// Ensure study1 is displayed
await waitFor(() =>
expect(screen.getAllByText(/^study\d+$/)).toHaveLength(1));
fireEvent.click(screen.getByText('study1'));
// Ensure series1 is displayed
await waitFor(() =>
expect(screen.getAllByText(/^series\d+$/)).toHaveLength(1));
fireEvent.click(screen.getByText('series1'));
// Confirm that breadcrumbs are all displaying correctly
expect(screen.queryByText('project2')).not.toBeNull();
expect(screen.queryByText('location5')).not.toBeNull();
expect(screen.queryByText('dataset3')).not.toBeNull();
expect(screen.queryByText('dicomStore4')).not.toBeNull();
expect(screen.queryByText('study1')).not.toBeNull();
expect(screen.queryByText('series1')).not.toBeNull();
// Confirm that clicking a breadcrumb resets state back to
// search list
fireEvent.click(screen.getByText('project2'));
await waitFor(() =>
expect(screen.queryByText('Select Project')).not.toBeNull());
await waitFor(() =>
expect(screen.getAllByText(/^project\d+$/)).toHaveLength(5));
}, 10000);
Example #19
Source File: Crisp.test.jsx From react-crisp with Apache License 2.0 | 5 votes |
test('Crisp load', async () => {
await render(<Crisp crispWebsiteId="foo-website-id-load" />);
await waitFor(() => expect(global.$crisp).toBeDefined());
await waitFor(() => expect(document.querySelector('.crisp-client')).toBeDefined());
await waitFor(() => expect(global.CRISP_WEBSITE_ID).toMatch(/foo-website-id-load/));
});
Example #20
Source File: RunTaskButton.tests.js From tasks-frontend with Apache License 2.0 | 5 votes |
describe('RunTaskButton', () => {
let props;
beforeEach(() => {
props = {
className: '',
slug: availableTasksTableItems[0].slug,
isFirst: true,
openTaskModal: jest.fn(),
variant: 'primary',
};
});
it('should render correctly', () => {
const { asFragment } = render(
<MemoryRouter keyLength={0}>
<RunTaskButton {...props} />
</MemoryRouter>
);
expect(asFragment()).toMatchSnapshot();
});
it('should render Run task again', () => {
props.isFirst = false;
const { asFragment } = render(
<MemoryRouter keyLength={0}>
<RunTaskButton {...props} />
</MemoryRouter>
);
expect(asFragment()).toMatchSnapshot();
});
it('should handle onClick', async () => {
render(
<MemoryRouter keyLength={0}>
<RunTaskButton {...props} />
</MemoryRouter>
);
await waitFor(() =>
userEvent.click(screen.getByLabelText('taska-run-task-button'))
);
expect(props.openTaskModal).toHaveBeenCalledWith(props.slug);
});
});
Example #21
Source File: ActionEntity.test.jsx From sgmr-service with MIT License | 5 votes |
describe('ActionEntity', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should render page and elements correctly', () => {
renderPage();
expect(screen.getByText('Are you sure you want to delete this pleasure craft?')).toBeInTheDocument();
expect(screen.getByText('Continue')).toBeInTheDocument();
});
it('should redirect when user click no on deletion confirmation', () => {
renderPage();
fireEvent.click(screen.getByTestId('confirm-no'));
fireEvent.click(screen.getByText('Continue'));
expect(mockHistoryReplace).toHaveBeenCalled();
expect(mockHistoryReplace).toBeCalledWith('/pleasure-crafts');
});
it('should go back when user clicks back', () => {
renderPage();
fireEvent.click(screen.getByText('Back'));
expect(mockHistoryGoBack).toHaveBeenCalled();
});
it('should invoke delete function on submit', async () => {
renderPage();
fireEvent.click(screen.getByTestId('confirm-yes'));
fireEvent.click(screen.getByText('Continue'));
await waitFor(() => {
expect(mockApiHook).toHaveBeenCalled();
expect(mockApiHook).toHaveBeenCalledWith(`${VESSELS_URL}/1a2b3c`);
});
});
it('should handle errors correctly', async () => {
mockApiHook = jest.fn().mockImplementation(() => {
throw Object.assign(
new Error('Error'),
{ response: 'Foo' },
);
});
renderPage();
fireEvent.click(screen.getByTestId('confirm-yes'));
fireEvent.click(screen.getByText('Continue'));
await waitFor(() => {
expect(screen.getByText('Cannot delete this pleasure craft right now, try again later')).toBeInTheDocument();
});
});
it('should handle cancelling voyage report', async () => {
renderPage({
title: 'Success',
heading: 'Voyage plan successfully cancelled.',
entity: 'voyage plan',
baseURL: VOYAGE_REPORT_URL,
redirectURL: '/voyage-plans',
apiHook: mockApiHook,
apiHookConfig: [{ status: VOYAGE_STATUSES.PRE_CANCELLED }],
action: 'Cancel',
});
fireEvent.click(screen.getByTestId('confirm-yes'));
fireEvent.click(screen.getByText('Continue'));
await waitFor(() => {
expect(mockApiHook).toHaveBeenCalledWith(`${VOYAGE_REPORT_URL}/1a2b3c`, { status: VOYAGE_STATUSES.PRE_CANCELLED });
});
});
});
Example #22
Source File: App.test.js From ReactCookbook-source with MIT License | 5 votes |
describe('App', () => {
it('should tell you when you win', async () => {
// Given we've rendered the app
render(<App/>);
// When we enter the correct answer
const number1 = screen.getByTestId('number1').textContent;
const number2 = screen.getByTestId('number2').textContent;
const input = screen.getByLabelText(/guess:/i);
const submitButton = screen.getByText('Submit');
user.type(input, '' + (parseFloat(number1) * parseFloat(number2)));
user.click(submitButton);
// Then we are told that we've won
// screen.getByText(/won/i);
await waitFor(() => screen.findByText(/won/i), {timeout: 4000});
})
it('should disable the question when a result is displayed', () => {
render(<App/>);
const input = screen.getByLabelText(/guess:/i);
user.type(input, '1');
const submitButton = screen.getByText('Submit');
user.click(submitButton);
expect(input.disabled).toBe(true);
expect(submitButton.disabled).toBe(true);
expect(screen.getByLabelText(/guess:/i)).toHaveValue(null);
})
it('should restart the game if you press refresh', () => {
render(<App/>);
const input = screen.getByLabelText(/guess:/i);
user.type(input, '1');
const submitButton = screen.getByText('Submit');
const refreshButton = screen.getByText('Submit');
user.click(submitButton);
expect(input.disabled).toBe(true);
expect(submitButton.disabled).toBe(true);
expect(screen.getByLabelText(/guess:/i)).toHaveValue(null);
expect(input.disabled).toBe(true);
})
it('should tell you that you entered the right answer', async () => {
// Given we've rendered the app
makeRandomAlways(0.5);
render(<App/>);
// When we enter the correct answer
const input = screen.getByLabelText(/guess:/i);
const submitButton = screen.getByText('Submit');
user.type(input, '36');
user.click(submitButton);
// Then we are told that we've won
await waitFor(() => screen.findByText(/won/i), {timeout: 4000});
})
});
Example #23
Source File: test.js From emgoto.com with MIT License | 5 votes |
describe('Comments component', () => {
test('should display nothing if article ID is not passed in', async () => {
render(<Comments />);
// Since our component renders async, we need to wait to make sure it doesn't pop in
await waitFor(() => {}, { timeout: 100 });
const commentsLink = screen.queryByRole('link');
expect(commentsLink).toBeNull();
});
test('should display nothing if DEV API fails to return data', async () => {
fetch.mockReturnValue(Promise.reject('API is down'));
render(<Comments devArticleId={123} />);
// Since our component renders async, we need to wait to make sure it doesn't pop in
await waitFor(() => {}, { timeout: 100 });
const commentsLink = screen.queryByRole('link');
expect(commentsLink).toBeNull();
});
test('should display nothing if DEV API returns error due to wrong ID', async () => {
json.mockReturnValue(
Promise.resolve({ error: 'not found', status: 404 }),
);
render(<Comments devArticleId={123} />);
// Since our component renders async, we need to wait to make sure it doesn't pop in
await waitFor(() => {}, { timeout: 100 });
const commentsLink = screen.queryByRole('link');
expect(commentsLink).toBeNull();
});
test('should display number of comments with link to article', async () => {
render(<Comments devArticleId={123} />);
await waitFor(() => {
expect(json).toHaveBeenCalledTimes(1);
});
const commentsLink = await screen.findByRole('link');
expect(commentsLink).toHaveTextContent('5 comments');
expect(commentsLink.href).toBe(COMMENTS_URL);
});
test('should display prompt to leave a comment if there are no comments', async () => {
json.mockReturnValue(
Promise.resolve({ comments_count: 0, url: MOCK_URL }),
);
render(<Comments devArticleId={123} />);
await waitFor(() => {
expect(json).toHaveBeenCalledTimes(1);
});
const commentsLink = await screen.findByRole('link');
expect(commentsLink).toHaveTextContent('Comment on DEV');
expect(commentsLink.href).toBe(COMMENTS_URL);
});
});
Example #24
Source File: emulator.test.js From android-emulator-webrtc with Apache License 2.0 | 5 votes |
describe("The emulator", () => {
let fakeScreen;
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
RtcService.mockClear();
EmulatorControllerService.mockClear();
});
test("Creates gRPC services", async () => {
let state;
renderIgnoringUnstableFlushDiscreteUpdates(
<Emulator uri="/test" width={300} height={300} />
);
expect(EmulatorControllerService).toHaveBeenCalled();
expect(RtcService).toHaveBeenCalled();
// Shipped out a gps call
});
test("Tries to establish a webrtc connection", async () => {
let state;
renderIgnoringUnstableFlushDiscreteUpdates(
<Emulator
uri="/test"
width={300}
height={300}
onStateChange={(e) => {
state = e;
}}
/>
);
await waitFor(() => state === "connecting");
expect(RtcService).toHaveBeenCalled();
});
test("Sends a gps location to the emulator", async () => {
// Let's go to Seattle!
renderIgnoringUnstableFlushDiscreteUpdates(
<Emulator
uri="/test"
width={300}
height={300}
gps={{ latitude: 47.6062, longitude: 122.3321 }}
/>
);
const setGps = EmulatorControllerService.mock.instances[0].setGps;
expect(setGps).toHaveBeenCalled();
const location = new Proto.GpsState();
location.setLatitude(47.6062);
location.setLongitude(122.3321);
location.setAltitude(undefined);
location.setBearing(undefined);
location.setSpeed(undefined);
expect(setGps).toHaveBeenCalledWith(location);
});
test("The png view requests images", async () => {
let pngCall = false
EmulatorControllerService.mockImplementation(() => {
return {
streamScreenshot: jest.fn((request) => {
pngCall = true
return { on: jest.fn(), cancel: jest.fn() };
}),
getStatus: jest.fn(() => {}),
};
});
render(<Emulator uri="/test" width={300} height={300} view="png" />);
expect(pngCall).toBeTruthy()
});
});
Example #25
Source File: PlotContainer.test.jsx From ui with MIT License | 5 votes |
describe('PlotContainer', () => {
beforeEach(async () => {
jest.clearAllMocks();
store = makeStore();
await store.dispatch(loadPlotConfig(experimentId, plotUuid, plotType));
});
it('Renders itself and its children properly', async () => {
renderPlotContainer(store);
expect(screen.getByText('Mock plot')).toBeInTheDocument();
expect(screen.getByText('Reset')).toBeInTheDocument();
});
it('Renders extra toolbar button', async () => {
const toolbarText = 'Extra toolbar button';
renderPlotContainer(store, { extraToolbarControls: <div>{toolbarText}</div> });
expect(screen.getByText(toolbarText)).toBeInTheDocument();
});
it('Renders extra control panels', async () => {
const controlPanelText = 'control panel text';
renderPlotContainer(store, { extraControlPanels: <div>{controlPanelText}</div> });
expect(screen.getByText(controlPanelText)).toBeInTheDocument();
});
it('Not showing reset removes the reset button', async () => {
renderPlotContainer(store, { showReset: false });
expect(screen.queryByText('Reset')).toBeNull();
});
it('Renders tooltips', async () => {
renderPlotContainer(store, { plotInfo: 'plot information' });
// There should be an information button on the document
const tooltip = screen.getByRole('button', { name: 'info-circle' });
expect(tooltip).toBeInTheDocument();
// Hovering over the element should show tooltip
userEvent.hover(tooltip);
await waitFor(() => {
expect(screen.getByText('plot information')).toBeInTheDocument();
});
});
it('Clicking reset button resets the plot config', async () => {
const defaultWidth = initialPlotConfigStates[plotType].dimensions.width;
renderPlotContainer(store);
// Reset button should be disabled because there are no changes to config
expect(screen.getByText('Reset').closest('button')).toBeDisabled();
act(() => {
store.dispatch(updatePlotConfig(plotUuid, { dimensions: { width: 1000 } }));
});
// Check that plot config has changed
const changedWidth = store.getState().componentConfig[plotUuid].config.dimensions.width;
expect(changedWidth).not.toEqual(defaultWidth);
// Clicking reset should reset the width
expect(screen.getByText('Reset').closest('button')).not.toBeDisabled();
userEvent.click(screen.getByText('Reset'));
await waitFor(() => {
const resetWidth = store.getState().componentConfig[plotUuid].config.dimensions.width;
expect(resetWidth).toEqual(defaultWidth);
});
});
});
Example #26
Source File: auth.test.js From what-front with MIT License | 5 votes |
describe('Auth', () => {
let formValues;
beforeEach(() => {
formValues = {
email: '[email protected]',
password: 'Testpassw!ord123',
};
});
it('should render component', () => {
const { container } = render(<Router><Auth /></Router>);
const authContainer = container.getElementsByClassName('container');
expect(authContainer).toMatchSnapshot();
});
it('should validate the form', async () => {
const { getByText, getAllByText } = render(<Router><Auth /></Router>);
const FORM_FIELD_AMOUNT = 2;
const submitButton = getByText('Sign in');
await waitFor(() => {
fireEvent.click(submitButton);
});
const errors = getAllByText('This field is required');
expect(errors).toHaveLength(FORM_FIELD_AMOUNT);
expect(errors).toMatchSnapshot();
});
it('should handle error receiving', () => {
useSelector.mockReturnValue({
isLoading: false,
error: 'Something went wrong',
loaded: true,
});
const { getByText } = render(<Router><Auth /></Router>);
const error = getByText('Something went wrong');
expect(error).toBeInTheDocument();
});
it('should submit the form with correct schema', async () => {
const { getByPlaceholderText, getByText } = render(<Router><Auth /></Router>);
const email = getByPlaceholderText('Email address');
const password = getByPlaceholderText('Password');
const submitButton = getByText('Sign in');
const signIn = useActions(login);
fireEvent.change(email, {
target: {
value: formValues.email,
},
});
fireEvent.change(password, {
target: {
value: formValues.password,
},
});
await waitFor(() => {
fireEvent.click(submitButton);
});
signIn({
email: email.value,
password: password.value,
});
expect(signIn).toHaveBeenCalledWith(formValues);
});
});
Example #27
Source File: combobox-tests.jest.js From monday-ui-react-core with MIT License | 5 votes |
describe("Combobox tests", () => {
beforeEach(() => {
jest.useFakeTimers("modern");
});
afterEach(() => {
jest.useRealTimers();
});
const mockOptions = [
{ value: "orange", label: "Orange" },
{ value: "yellow", label: "Yellow" }
];
it("should call item on click callback func when onClick", () => {
const onClickMock = jest.fn();
const { getByLabelText } = render(<Combobox onClick={onClickMock} options={mockOptions} />);
fireEvent.click(getByLabelText("Yellow"));
expect(onClickMock.mock.calls.length).toBe(1);
expect(onClickMock).toHaveBeenCalledWith(expect.objectContaining({ value: "yellow", label: "Yellow" }));
});
it("should call callback func when onOptionHover", () => {
const onMouseOverMock = jest.fn();
const { getByLabelText } = render(<Combobox onOptionHover={onMouseOverMock} options={mockOptions} />);
fireEvent.mouseOver(getByLabelText("Yellow"));
expect(onMouseOverMock.mock.calls.length).toBe(1);
});
it("should call callback func when onOptionLeave", () => {
const onMouseLeaveMock = jest.fn();
const { getByLabelText } = render(<Combobox onOptionLeave={onMouseLeaveMock} options={mockOptions} />);
fireEvent.mouseLeave(getByLabelText("Yellow"));
expect(onMouseLeaveMock.mock.calls.length).toBe(1);
});
it("should call callback func when noResultsRenderer", async () => {
const noResRendereMock = jest.fn();
const { getByLabelText } = render(<Combobox noResultsRenderer={noResRendereMock} options={mockOptions} />);
const input = getByLabelText("Search for content");
expect(noResRendereMock.mock.calls.length).toBe(0);
fireEvent.change(input, { target: { value: "No text in option" } });
await waitFor(() => expect(noResRendereMock.mock.calls.length).toBe(1));
});
it("should display no results message", async () => {
const noRes = "NO MESSAGE";
const { getByLabelText } = render(<Combobox options={mockOptions} noResultsMessage={noRes} />);
const input = getByLabelText("Search for content");
fireEvent.change(input, { target: { value: "No text in option" } });
await waitFor(() => expect(screen.getByText(noRes)).toBeInstanceOf(Node));
});
it("should call onAddNew func when add new", async () => {
const onAddMock = jest.fn();
const { getByLabelText } = render(<Combobox onAddNew={onAddMock} options={mockOptions} />);
const input = getByLabelText("Search for content");
fireEvent.change(input, { target: { value: "No text in option" } });
await waitFor(() => {
fireEvent.click(screen.getByText("Add new"));
expect(onAddMock.mock.calls.length).toBe(1);
});
});
});
Example #28
Source File: checkout-form.js From muffinsplantshop with BSD Zero Clause License | 5 votes |
describe('Shows shipping and billing details with valid form submission', () => {
test('where shipping and billing details are the same', async () => {
render(<CheckoutForm />);
fireEvent.change(screen.getByLabelText(/first/i), { target: { value: shippingValues.firstName } });
fireEvent.change(screen.getByLabelText(/last/i), { target: { value: shippingValues.lastName } });
fireEvent.change(screen.getByLabelText(/address.+(1|one)/i), { target: { value: shippingValues.addressOne } });
fireEvent.change(screen.getByLabelText(/municipality/i), { target: { value: shippingValues.municipality } });
fireEvent.change(screen.getByLabelText(/province/i), { target: { value: shippingValues.provinceTerritory } });
fireEvent.change(screen.getByLabelText(/code/i), { target: { value: shippingValues.postalCode } });
fireEvent.change(screen.getByLabelText(/phone/i), { target: { value: shippingValues.phone } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: shippingValues.email } });
await waitFor(() => {
const submit = screen.getByTestId("submit-shipping-button");
fireEvent.click(submit);
})
Object.entries(shippingValues).forEach(([key, value]) => {
const regex = new RegExp(value);
if(['email', 'shipping', 'phone'].includes(key)) {
expect(screen.queryByText(regex)).toBeInTheDocument();
} else {
expect(screen.getAllByText(regex).length).toEqual(2);
}
});
await waitFor(() => {
const submit = screen.getByTestId("submit-billing-button");
fireEvent.click(submit);
})
expect(screen.queryByText("Payment is not available in this demo")).toBeInTheDocument();
})
test('where shipping and billing details are different', async () => {
render(<CheckoutForm />);
fireEvent.change(screen.getByLabelText(/first/i), { target: { value: shippingValues.firstName } });
fireEvent.change(screen.getByLabelText(/last/i), { target: { value: shippingValues.lastName } });
fireEvent.change(screen.getByLabelText(/address.+(1|one)/i), { target: { value: shippingValues.addressOne } });
fireEvent.change(screen.getByLabelText(/municipality/i), { target: { value: shippingValues.municipality } });
fireEvent.change(screen.getByLabelText(/province/i), { target: { value: shippingValues.provinceTerritory } });
fireEvent.change(screen.getByLabelText(/code/i), { target: { value: shippingValues.postalCode } });
fireEvent.change(screen.getByLabelText(/phone/i), { target: { value: shippingValues.phone } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: shippingValues.email } });
await waitFor(() => {
const submit = screen.getByTestId("submit-shipping-button");
fireEvent.click(submit);
})
const toggleSameAddress = await screen.findByLabelText(/My billing address is the same/i);
fireEvent.click(toggleSameAddress);
fireEvent.change(screen.getByLabelText(/first/i), { target: { value: billingValues.firstName } });
fireEvent.change(screen.getByLabelText(/last/i), { target: { value: billingValues.lastName } });
fireEvent.change(screen.getByLabelText(/address.+(1|one)/i), { target: { value: billingValues.addressOne } });
fireEvent.change(screen.getByLabelText(/municipality/i), { target: { value: billingValues.municipality } });
fireEvent.change(screen.getByLabelText(/province/i), { target: { value: billingValues.provinceTerritory } });
fireEvent.change(screen.getByLabelText(/code/i), { target: { value: billingValues.postalCode } });
await waitFor(() => {
const submit = screen.getByTestId("submit-billing-button");
fireEvent.click(submit);
})
Object.entries(shippingValues).forEach(([, value]) => {
const regex = new RegExp(value);
expect(screen.getByText(regex)).toBeInTheDocument();
});
Object.entries(billingValues).forEach(([, value]) => {
const regex = new RegExp(value);
expect(screen.getByText(regex)).toBeInTheDocument();
})
})
})
Example #29
Source File: ActionsDropdown.test.jsx From frontend-app-discussions with GNU Affero General Public License v3.0 | 5 votes |
describe('ActionsDropdown', () => {
beforeEach(async () => {
initializeMockApp({
authenticatedUser: {
userId: 3,
username: 'abc123',
administrator: false,
roles: [],
},
});
});
it.each(buildTestContent())('can open drop down if enabled', async (commentOrPost) => {
renderComponent(commentOrPost, { disabled: false });
const openButton = await findOpenActionsDropdownButton();
await act(async () => {
fireEvent.click(openButton);
});
await waitFor(() => expect(screen.queryByTestId('actions-dropdown-modal-popup')).toBeInTheDocument());
});
it.each(buildTestContent())('can not open drop down if disabled', async (commentOrPost) => {
renderComponent(commentOrPost, { disabled: true });
const openButton = await findOpenActionsDropdownButton();
await act(async () => {
fireEvent.click(openButton);
});
await waitFor(() => expect(screen.queryByTestId('actions-dropdown-modal-popup')).not.toBeInTheDocument());
});
describe.each(canPerformActionTestData)('Actions', ({
testFor, action, label, reason, ...commentOrPost
}) => {
describe(`for ${testFor}`, () => {
it(`can "${label}" when allowed`, async () => {
const mockHandler = jest.fn();
renderComponent(
commentOrPost,
{ actionHandlers: { [action]: mockHandler } },
);
const openButton = await findOpenActionsDropdownButton();
await act(async () => {
fireEvent.click(openButton);
});
await waitFor(() => expect(screen.queryByText(label))
.toBeInTheDocument());
await act(async () => {
fireEvent.click(screen.queryByText(label));
});
expect(mockHandler).toHaveBeenCalled();
});
});
});
describe.each(canNotPerformActionTestData)('Actions', ({
testFor, action, label, reason, ...commentOrPost
}) => {
describe(`for ${testFor}`, () => {
it(`can't "${label}" when ${reason}`, async () => {
renderComponent(commentOrPost);
const openButton = await findOpenActionsDropdownButton();
await act(async () => {
fireEvent.click(openButton);
});
await waitFor(() => expect(screen.queryByText(label)).not.toBeInTheDocument());
});
});
});
});