@testing-library/react#waitForElementToBeRemoved TypeScript Examples
The following examples show how to use
@testing-library/react#waitForElementToBeRemoved.
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: test-utils.tsx From react-loosely-lazy with Apache License 2.0 | 7 votes |
testRender = async ({
lazyMethod,
loader,
phase = PHASE.PAINT,
ssr,
text = 'Default Component',
}: TestRenderOptions) => {
const LazyTestComponent = lazyMethod(loader ?? createClientLoader(), {
ssr,
});
const { queryByText } = render(
<App phase={phase}>
<LazySuspense fallback="Loading...">
<LazyTestComponent />
</LazySuspense>
</App>
);
if (isNodeEnvironment()) {
expect(queryByText('Loading...')).not.toBeInTheDocument();
} else {
expect(queryByText('Loading...')).toBeInTheDocument();
await waitForElementToBeRemoved(() => queryByText('Loading...'));
}
expect(queryByText(text)).toBeInTheDocument();
}
Example #2
Source File: test-utils.tsx From react-loosely-lazy with Apache License 2.0 | 7 votes |
testFallbackRender = async ({
lazyMethod,
loader,
phase = PHASE.PAINT,
ssr,
}: TestFallbackRenderOptions) => {
const LazyTestComponent = lazyMethod(
loader ?? isNodeEnvironment() ? createServerLoader() : createClientLoader(),
ssr == null ? undefined : { ssr }
);
const { queryByText } = render(
<App phase={phase}>
<LazySuspense fallback="Loading...">
<LazyTestComponent />
</LazySuspense>
</App>
);
if (isNodeEnvironment()) {
expect(queryByText('Loading...')).toBeInTheDocument();
} else {
expect(queryByText('Loading...')).toBeInTheDocument();
await waitForElementToBeRemoved(() => queryByText('Loading...')).catch(
() => {
// We expect the loading state to remain, and this should timeout
}
);
expect(queryByText('Default Component')).not.toBeInTheDocument();
}
}
Example #3
Source File: test_utils.tsx From firebase-tools-ui with Apache License 2.0 | 7 votes |
/**
* Wait for MDC dialogs to be fully closed, so no DOM changes happen outside
* our control and trigger warnings of not wrapped in act(...) etc.
*/
export async function waitForDialogsToClose() {
// TODO: Change to waitFor once we migrate to react-testing-library@10.
await waitForElementToBeRemoved(() =>
document.querySelector('.mdc-dialog--closing')
);
}
Example #4
Source File: YearsStatusBarMethods.tsx From UsTaxes with GNU Affero General Public License v3.0 | 6 votes |
setYear = async (y: TaxYear): Promise<void> => {
this.openDropdown()
await waitFor(() => {
expect(this.yearSelectConfirm()).toBeInTheDocument()
})
userEvent.selectOptions(this.yearSelect(), [y])
userEvent.click(this.yearSelectConfirm()!)
await waitForElementToBeRemoved(() => this.yearSelectConfirm())
}
Example #5
Source File: CloneDialog.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
setup = async () => {
const onComplete = jest.fn();
const parent = fakeReference({ key: 'parent', path: 'parent' });
const ROOT_REF = fakeReference({ key: null, parent: null });
const ref = fakeReference({
parent,
key: 'to_clone',
path: 'parent/to_clone',
data: { bool: true, number: 1234, string: 'a string', json: { a: 'b' } },
});
(ROOT_REF.child as jest.Mock).mockReturnValue(ref);
ref.root = ROOT_REF;
(ref.child as jest.Mock).mockReturnValue(ref);
const { getByText, getByLabelText, getByTestId } =
await renderDialogWithFirestore(async (firestore) => (
<CloneDialog onComplete={onComplete} realtimeRef={ref} />
));
await waitForElementToBeRemoved(() => getByText(/Loading/));
return { ref, onComplete, getByLabelText, getByText, getByTestId };
}
Example #6
Source File: Collection.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('deletes collection and nested data when requested', async () => {
const { findByRole, queryByText } = await renderWithFirestore(
async (firestore) => {
const collectionRef = firestore.collection('whose-stuff');
const docRef = collectionRef.doc('cool-doc');
await docRef.set({ myField: 1 });
return (
<>
<Collection collection={collectionRef} />
<Portal />
</>
);
}
);
const menu = await findByRole('button', { name: 'Menu' });
await act(() => {
menu.click();
return delay(200);
});
(confirm as jest.Mock).mockResolvedValueOnce(true);
const deleteDocument = await findByRole('menuitem', {
name: 'Delete collection',
});
act(() => {
deleteDocument.click();
});
await waitForElementToBeRemoved(() => queryByText(/cool-doc/), {
timeout: 2000,
});
expect(queryByText(/cool-doc/)).toBeNull();
}, 10000);
Example #7
Source File: Document.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('shows the selected document-collection', async () => {
const { getAllByTestId, getByText } = await renderWithFirestore(
async (firestore) => {
const documentRef = firestore.doc('foo/bar');
await documentRef.collection('sub').doc('doc').set({ spam: 'eggs' });
return (
<Route path="/firestore/data/foo/bar">
<Document reference={documentRef} />
<Portal />
</Route>
);
},
{
path: '/firestore/data/foo/bar/sub/doc',
}
);
await waitForElementToBeRemoved(() => getByText(/Loading collection$/));
await waitFor(() => getAllByTestId('collection-list').length > 1);
expect(getAllByTestId('collection-list').length).toBe(2);
expect(getByText(/eggs/)).not.toBeNull();
});
Example #8
Source File: Document.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('shows the selected document-collection when there are collection and document ids with special characters', async () => {
const { getAllByTestId, getByText } = await renderWithFirestore(
async (firestore) => {
const documentRef = firestore.doc('foo@#$/bar@#$');
await documentRef
.collection('sub@#$')
.doc('doc@#$')
.set({ spam: 'eggs' });
return (
<Route path="/firestore/data/foo%40%23%24/bar%40%23%24">
<Document reference={documentRef} />
<Portal />
</Route>
);
},
{
path: '/firestore/data/foo%40%23%24/bar%40%23%24/sub%40%23%24/doc%40%23%24',
}
);
await waitForElementToBeRemoved(() => getByText(/Loading collection$/));
await waitFor(() => getAllByTestId('collection-list').length > 1);
expect(getAllByTestId('collection-list').length).toBe(2);
expect(getByText(/eggs/)).not.toBeNull();
});
Example #9
Source File: FirestoreEmulatedApiProvider.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('should clear the database', async () => {
const TestResults = ({
docRef,
}: {
docRef: firebase.firestore.DocumentReference;
}) => {
const { data } = useFirestoreDocData(docRef);
const eject = useEjector();
return (
<>
<div data-testid="data">{JSON.stringify(data)}</div>
<button onClick={() => eject()}>Clear</button>
</>
);
};
const { getByText, getByTestId } = await renderWithFirestore(
async (firestore) => {
const docRef = firestore.doc('top/doc');
await docRef.set({ a: 1 });
return <TestResults docRef={docRef} />;
}
);
await waitFor(() => getByText(/"a":1/));
act(() => {
getByText(/Clear/).click();
});
await waitForElementToBeRemoved(() => getByText(/"a":1/));
expect(getByTestId(/data/).textContent).not.toContain('"a":1');
});
Example #10
Source File: Snackbar.test.tsx From atlas with GNU General Public License v3.0 | 6 votes |
describe('Snackar', async () => {
it('Display snackbar', async () => {
const { getByText } = render(<TestElement />, {
wrapper: ({ children }) => (
<BrowserRouter>
{children}
<Snackbars />
</BrowserRouter>
),
})
fireEvent.click(screen.getByRole('button'))
getByText(props.title ?? '')
getByText(props.description ?? '')
getByText(props.actionText ?? '')
await waitForElementToBeRemoved(() => getByText(props.title ?? ''))
})
})
Example #11
Source File: ConclusionsPanel.test.tsx From abacus with GNU General Public License v2.0 | 6 votes |
test('opens and cancels edit dialog', async () => {
const experiment = Fixtures.createExperimentFull()
render(<ConclusionsPanel experiment={experiment} experimentReloadRef={experimentReloadRef} />)
fireEvent.click(screen.getByRole('button', { name: /Edit/ }))
await waitFor(queryEditDialog)
fireEvent.click(screen.getByRole('button', { name: /Cancel/ }))
await waitForElementToBeRemoved(queryEditDialog)
})
Example #12
Source File: ConclusionsPanel.test.tsx From abacus with GNU General Public License v2.0 | 6 votes |
test('opens and saves edit dialog', async () => {
const experiment = Fixtures.createExperimentFull()
render(<ConclusionsPanel experiment={experiment} experimentReloadRef={experimentReloadRef} />)
mockedExperimentsApi.patch.mockClear().mockReset()
mockedExperimentsApi.patch.mockImplementation(async () => experiment)
// First round: Save empty form.
fireEvent.click(screen.getByRole('button', { name: /Edit/ }))
await waitFor(queryEditDialog)
fireEvent.click(screen.getByRole('button', { name: /Save/ }))
await waitForElementToBeRemoved(queryEditDialog)
expect(mockedExperimentsApi.patch).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.patch).toHaveBeenLastCalledWith(1, { endReason: '' })
// Second round: Add some details.
mockedExperimentsApi.patch.mockClear()
fireEvent.click(screen.getByRole('button', { name: /Edit/ }))
await waitFor(queryEditDialog)
await changeFieldByRole('textbox', /Reason/, 'The experiment ended')
await changeFieldByRole('textbox', /Conclusion/, 'https://www.conclusions.com/')
fireEvent.click(screen.getByLabelText(/test/))
fireEvent.click(screen.getByRole('button', { name: /Save/ }))
await waitForElementToBeRemoved(queryEditDialog)
expect(mockedExperimentsApi.patch).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.patch).toHaveBeenLastCalledWith(1, {
conclusionUrl: 'https://www.conclusions.com/',
deployedVariationId: 2,
endReason: 'The experiment ended',
})
})
Example #13
Source File: FirestoreEmulatedApiProvider.test.tsx From firebase-tools-ui with Apache License 2.0 | 5 votes |
it('should recursively delete under path', async () => {
const TestResults = ({
docRef,
nestedRef,
}: {
docRef: firebase.firestore.DocumentReference;
nestedRef: firebase.firestore.DocumentReference;
}) => {
const { data } = useFirestoreDocData(docRef);
const nested = useFirestoreDocData(nestedRef);
const recursiveDelete = useRecursiveDelete();
return (
<>
<div data-testid="data">{JSON.stringify(data)}</div>
<div data-testid="nestedData">{JSON.stringify(nested.data)}</div>
<button onClick={() => recursiveDelete(docRef)}>Delete</button>
</>
);
};
const { getByText, getByTestId, findByText } = await renderWithFirestore(
async (firestore) => {
const docRef = firestore.doc('top/doc');
await docRef.set({ a: 1 });
const nestedRef = docRef.collection('nested').doc('nestedDoc');
await nestedRef.set({ b: 2 });
return <TestResults docRef={docRef} nestedRef={nestedRef} />;
}
);
await findByText(/"a":1/);
await findByText(/"b":2/);
act(() => {
getByText(/Delete/).click();
});
await waitForElementToBeRemoved(() => getByText(/"b":2/));
expect(getByTestId(/data/).textContent).not.toContain('"a":1');
expect(getByTestId(/nestedData/).textContent).not.toContain('"b":2');
});
Example #14
Source File: Footer.test.tsx From form-pa with GNU Affero General Public License v3.0 | 5 votes |
describe("render modals", () => {
const reviewModalTestID = "review-modal";
const qrModalTestID = "qr-modal";
it("renders qr modal", async () => {
const { getByTestId } = render(<Footer formRef={mockRef}/>);
const qrButton = getByTestId(qrButtonTestID);
userEvent.click(qrButton);
expect(await screen.findByTestId(qrModalTestID)).toBeInTheDocument();
});
it("closes the qr modal on Close button click", async () => {
render(<Footer formRef={mockRef}/>);
const qrButton = await screen.findByTestId(qrButtonTestID);
userEvent.click(qrButton);
expect(screen.queryByTestId(qrModalTestID)).toBeInTheDocument();
expect(screen.getByTestId("close-qr-modal")).toBeInTheDocument();
const closeButton = await screen.findByTestId("close-qr-modal");
userEvent.click(closeButton);
await waitForElementToBeRemoved(() => screen.queryByTestId(qrModalTestID));
expect(screen.queryByTestId(qrModalTestID)).not.toBeInTheDocument();
});
it("renders review modal", async () => {
const { getByTestId } = render(<Footer formRef={mockRef}/>);
const saveButton = getByTestId(saveButtonTestID);
userEvent.click(saveButton);
expect(await screen.findByTestId(reviewModalTestID)).toBeInTheDocument();
});
it("closes the review modal on Close button click", async () => {
render(<Footer formRef={mockRef}/>);
const saveButton = await screen.findByTestId(saveButtonTestID);
userEvent.click(saveButton);
expect(screen.queryByTestId(reviewModalTestID)).toBeInTheDocument();
expect(screen.getByTestId("close-review-modal")).toBeInTheDocument();
const closeButton = await screen.findByTestId("close-review-modal");
userEvent.click(closeButton);
await waitForElementToBeRemoved(() =>
screen.queryByTestId(reviewModalTestID)
);
expect(screen.queryByTestId(reviewModalTestID)).not.toBeInTheDocument();
});
});
Example #15
Source File: CreateAccount.slow.spec.tsx From crust-apps with Apache License 2.0 | 5 votes |
describe.only('--SLOW--: Account Create', () => {
it('created account is added to list', async () => {
const { findByTestId, findByText, queryByText } = renderAccounts();
const addAccountButton = await findByText('Add account', {}, { timeout: 5000 });
fireEvent.click(addAccountButton);
const isSeedSavedCheckbox = await findByText('I have saved my mnemonic seed safely');
const hiddenCheckbox = isSeedSavedCheckbox as HTMLInputElement;
fireEvent.click(hiddenCheckbox);
const nextStepButton = await findByText('Next', {}, { timeout: 4000 });
fireEvent.click(nextStepButton);
const accountNameInput = await findByTestId('name');
fireEvent.change(accountNameInput, { target: { value: 'my new account' } });
const passwordInput = await findByTestId('password');
fireEvent.change(passwordInput, { target: { value: 'password' } });
const passwordInput2 = await findByTestId('password (repeat)');
fireEvent.change(passwordInput2, { target: { value: 'password' } });
const toStep3Button = await findByText('Next', {}, { timeout: 4000 });
fireEvent.click(toStep3Button);
const createAnAccountButton = await findByText('Save', {}, { timeout: 4000 });
fireEvent.click(createAnAccountButton);
await waitForElementToBeRemoved(() => queryByText('Add an account via seed 3/3'));
expect(await findByText('MY NEW ACCOUNT')).toBeTruthy();
});
it('gives an error message when entering invalid derivation path', async () => {
const { findByTestId, findByText } = renderAccounts();
const addAccountButton = await findByText('Add account', {}, { timeout: 5000 });
fireEvent.click(addAccountButton);
const showAdvancedOptionsButton = await findByText('Advanced creation options', {}, { timeout: 5000 });
fireEvent.click(showAdvancedOptionsButton);
const derivationPathInput = await findByTestId('secret derivation path', {}, { timeout: 5000 });
fireEvent.change(derivationPathInput, { target: { value: '//abc//' } });
const errorMsg = await findByText('Unable to match provided value to a secret URI', {}, { timeout: 5000 });
expect(errorMsg).toBeTruthy();
});
});
Example #16
Source File: ExperimentRunButton.test.tsx From abacus with GNU General Public License v2.0 | 5 votes |
test('runs an experiment', async () => {
const experimentReloadRef: React.MutableRefObject<() => void> = { current: jest.fn() }
const experiment = Fixtures.createExperimentFull()
const { container } = render(<ExperimentRunButton {...{ experiment, experimentReloadRef }} />)
mockedExperimentsApi.changeStatus.mockReset()
mockedExperimentsApi.changeStatus.mockImplementationOnce(async () => undefined)
const firstRunButton = screen.getByRole('button', { name: /Launch/ })
// First Opening - We cancel
fireEvent.click(firstRunButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
expect(container).toMatchSnapshot()
const cancelButton = screen.getByRole('button', { name: /Cancel/ })
fireEvent.click(cancelButton)
await waitForElementToBeRemoved(cancelButton)
expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(0)
expect(experimentReloadRef.current).toHaveBeenCalledTimes(0)
// Second Opening - We run
fireEvent.click(firstRunButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
const cancelButton2nd = screen.getByRole('button', { name: /Cancel/ })
const allRunButtons = screen.getAllByRole('button', { name: /Launch/ })
allRunButtons.forEach((button) => fireEvent.click(button))
await waitForElementToBeRemoved(cancelButton2nd)
expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(1)
expect(experimentReloadRef.current).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.changeStatus).toMatchInlineSnapshot(`
[MockFunction] {
"calls": Array [
Array [
1,
"running",
],
],
"results": Array [
Object {
"type": "return",
"value": Promise {},
},
],
}
`)
})
Example #17
Source File: test-utils.tsx From react-loosely-lazy with Apache License 2.0 | 5 votes |
createErrorTests = ({
lazyMethod,
phase = PHASE.PAINT,
}: TestErrorBubblingOptions) => {
const clientError = new Error('ChunkLoadError');
if (!isNodeEnvironment()) {
it('does not retry when the global retry option is set to 0', async () => {
LooselyLazy.init({
retry: 0,
});
const loader = jest.fn(() => Promise.reject(clientError));
const LazyTestComponent = lazyMethod(loader);
const spy = jest.spyOn(console, 'error').mockImplementation(jest.fn);
const { queryByText } = render(
<ErrorBoundary fallback="Component failed to load...">
<App phase={phase}>
<LazySuspense fallback="Loading...">
<LazyTestComponent />
</LazySuspense>
</App>
</ErrorBoundary>
);
expect(queryByText('Loading...')).toBeInTheDocument();
await waitForElementToBeRemoved(() => queryByText('Loading...'));
spy.mockRestore();
expect(queryByText('Component failed to load...')).toBeInTheDocument();
expect(loader).toHaveBeenCalledTimes(1);
});
}
it('bubbles a loader error in the component lifecycle when the loader fails', async () => {
const moduleId = '@foo/bar';
const LazyTestComponent = lazyMethod(
() =>
isNodeEnvironment() ? require('404') : Promise.reject(clientError),
{
moduleId,
ssr: true,
}
);
const errors: Error[] = [];
const onError = (error: Error) => {
errors.push(error);
};
const spy = jest.spyOn(console, 'error').mockImplementation(jest.fn);
const { queryByText } = render(
<ErrorBoundary fallback="Component failed to load..." onError={onError}>
<App phase={phase}>
<LazySuspense fallback="Loading...">
<LazyTestComponent />
</LazySuspense>
</App>
</ErrorBoundary>
);
if (isNodeEnvironment()) {
expect(queryByText('Loading...')).not.toBeInTheDocument();
} else {
expect(queryByText('Loading...')).toBeInTheDocument();
await waitForElementToBeRemoved(() => queryByText('Loading...'));
}
spy.mockRestore();
expect(queryByText('Component failed to load...')).toBeInTheDocument();
expect(
errors.map(error => ({
error,
isLoaderError: isLoaderError(error),
}))
).toEqual([
{
error: isNodeEnvironment()
? expect.objectContaining({
code: 'MODULE_NOT_FOUND',
})
: clientError,
isLoaderError: true,
},
]);
});
}
Example #18
Source File: LabelTooltipDecorator.spec.tsx From symphony-ui-toolkit with Apache License 2.0 | 5 votes |
describe('LabelTooltipDecorator Component', () => {
const id = 'my-id-provided';
const tooltipText = 'This is a tooltip text';
const tooltipCloseLabel = 'Close';
describe('LabelTooltipDecorator test suite => ', () => {
it('render a TextField with default props and initial value and test if a input html tag is used', () => {
const wrapper = shallow(<LabelTooltipDecorator label="My label" />);
expect(wrapper.length).toEqual(1);
expect(wrapper.hasClass('tk-input-group__header')).toBe(true);
});
it('should display a label if provided', () => {
const id = 'textfield-1234567890';
let wrapper = shallow(<LabelTooltipDecorator/>);
expect(wrapper.find('label.tk-label').length).toBe(0);
wrapper = shallow(<LabelTooltipDecorator label="LABEL" htmlFor={id} />);
expect(wrapper.find('label.tk-label').text()).toEqual('LABEL');
expect(wrapper.find(`label[htmlFor="${id}"]`)).toHaveLength(1);
});
it('should have the style --required if showRequired is provided', () => {
const wrapper = shallow(
<LabelTooltipDecorator label="LABEL" showRequired/>
);
expect(wrapper.find('label.tk-label--required').length).toBe(1);
});
it('should display a tooltip if provided', () => {
let wrapper = shallow(<LabelTooltipDecorator />);
expect(wrapper.find('Icon').length).toBe(0);
wrapper = shallow(
<LabelTooltipDecorator
id={id}
tooltip={tooltipText}
tooltipCloseLabel={tooltipCloseLabel}
/>
);
expect(wrapper.find('Icon').length).toBe(1);
expect(wrapper.find('Icon').prop('iconName')).toBeDefined();
expect(wrapper.find('Tooltip').length).toBe(1);
expect(wrapper.find('Tooltip').prop('id')).toEqual(id);
expect(wrapper.find('Tooltip').prop('description')).toEqual(tooltipText);
expect(wrapper.find('Tooltip').prop('closeLabel')).toEqual(
tooltipCloseLabel
);
});
});
describe('should open and close the tooltip Component', () => {
it('should handleClickIcon be triggered', async () => {
const { getByText } = render(<LabelTooltipDecorator
id={id}
tooltip={tooltipText}
tooltipCloseLabel={tooltipCloseLabel}
/>
);
const icon = document.querySelector('i.tk-icon-info-round');
userEvent.click(icon);
const description = getByText(tooltipText);
await waitFor(() => expect(description).toBeTruthy());
const cta = getByText(tooltipCloseLabel);
userEvent.click(cta);
waitForElementToBeRemoved(cta);
});
});
});
Example #19
Source File: ExperimentDisableButton.test.tsx From abacus with GNU General Public License v2.0 | 5 votes |
test('disables an experiment', async () => {
const experimentReloadRef: React.MutableRefObject<() => void> = { current: jest.fn() }
const experiment = Fixtures.createExperimentFull()
const { container } = render(<ExperimentDisableButton {...{ experiment, experimentReloadRef }} />)
mockedExperimentsApi.changeStatus.mockReset()
mockedExperimentsApi.changeStatus.mockImplementationOnce(async () => undefined)
const firstDisableButton = screen.getByRole('button', { name: /Disable/ })
// First Opening - We cancel
fireEvent.click(firstDisableButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
expect(container).toMatchSnapshot()
const cancelButton = screen.getByRole('button', { name: /Cancel/ })
fireEvent.click(cancelButton)
await waitForElementToBeRemoved(cancelButton)
expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(0)
expect(experimentReloadRef.current).toHaveBeenCalledTimes(0)
// Second Opening - We disable
fireEvent.click(firstDisableButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
const cancelButton2nd = screen.getByRole('button', { name: /Cancel/ })
const allDisableButtons = screen.getAllByRole('button', { name: /Disable/ })
allDisableButtons.forEach((button) => fireEvent.click(button))
await waitForElementToBeRemoved(cancelButton2nd)
expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(1)
expect(experimentReloadRef.current).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.changeStatus).toMatchInlineSnapshot(`
[MockFunction] {
"calls": Array [
Array [
1,
"disabled",
],
],
"results": Array [
Object {
"type": "return",
"value": Promise {},
},
],
}
`)
})
Example #20
Source File: GeneralPanel.test.tsx From abacus with GNU General Public License v2.0 | 5 votes |
test('opens, submits and cancels edit dialog with running experiment', async () => {
const experiment = Fixtures.createExperimentFull({ status: Status.Running })
render(<GeneralPanel experiment={experiment} experimentReloadRef={experimentReloadRef} />)
mockedExperimentsApi.patch.mockReset()
mockedExperimentsApi.patch.mockImplementationOnce(async () => experiment)
const editButton = screen.getByRole('button', { name: /Edit/ })
fireEvent.click(editButton)
await waitFor(() => screen.getByRole('button', { name: /Save/ }))
await changeFieldByRole('textbox', /Experiment description/, 'Edited description.')
// This date was picked as it is after the fixture start date.
fireEvent.change(screen.getByLabelText(/End date/), { target: { value: '2020-10-20' } })
await changeFieldByRole('textbox', /Owner/, 'changed_owner-nickname')
const saveButton = screen.getByRole('button', { name: /Save/ })
fireEvent.click(saveButton)
await waitForElementToBeRemoved(saveButton)
expect(mockedExperimentsApi.patch).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.patch).toMatchInlineSnapshot(`
[MockFunction] {
"calls": Array [
Array [
1,
Object {
"description": "Edited description.",
"endDatetime": "2020-10-20",
"ownerLogin": "changed_owner-nickname",
},
],
],
"results": Array [
Object {
"type": "return",
"value": Promise {},
},
],
}
`)
fireEvent.click(editButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
const cancelButton = screen.getByRole('button', { name: /Cancel/ })
fireEvent.click(cancelButton)
await waitForElementToBeRemoved(cancelButton)
expect(mockedExperimentsApi.patch).toHaveBeenCalledTimes(1)
})
Example #21
Source File: GeneralPanel.test.tsx From abacus with GNU General Public License v2.0 | 5 votes |
test('checks edit dialog does not allow end datetime changes with disabled experiment', async () => {
const experiment = Fixtures.createExperimentFull({ status: Status.Disabled })
render(<GeneralPanel experiment={experiment} experimentReloadRef={experimentReloadRef} />)
mockedExperimentsApi.patch.mockReset()
mockedExperimentsApi.patch.mockImplementationOnce(async () => experiment)
const editButton = screen.getByRole('button', { name: /Edit/ })
fireEvent.click(editButton)
await waitFor(() => screen.getByRole('button', { name: /Save/ }))
await changeFieldByRole('textbox', /Experiment description/, 'Edited description.')
expect(screen.getByLabelText(/End date/)).toBeDisabled()
await changeFieldByRole('textbox', /Owner/, 'changed_owner-nickname')
const saveButton = screen.getByRole('button', { name: /Save/ })
fireEvent.click(saveButton)
await waitForElementToBeRemoved(saveButton)
expect(mockedExperimentsApi.patch).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.patch).toMatchInlineSnapshot(`
[MockFunction] {
"calls": Array [
Array [
1,
Object {
"description": "Edited description.",
"ownerLogin": "changed_owner-nickname",
},
],
],
"results": Array [
Object {
"type": "return",
"value": Promise {},
},
],
}
`)
})
Example #22
Source File: MetricAssignmentsPanel.test.tsx From abacus with GNU General Public License v2.0 | 5 votes |
test('opens, submits and cancels assign metric dialog', async () => {
const metrics = Fixtures.createMetrics(5)
const experiment = Fixtures.createExperimentFull({ status: Status.Running })
const experimentReloadRef: React.MutableRefObject<() => void> = { current: noop }
render(<MetricAssignmentsPanel {...{ experiment, metrics, experimentReloadRef }} />)
mockedExperimentsApi.assignMetric.mockReset()
// @ts-ignore
mockedExperimentsApi.assignMetric.mockImplementationOnce(async () => null)
const startAssignButton = screen.getByRole('button', { name: /Assign Metric/ })
fireEvent.click(startAssignButton)
await waitFor(() => screen.getByRole('button', { name: 'Assign' }))
const assignButton = screen.getByRole('button', { name: 'Assign' })
// We click it now to test the validation state
fireEvent.click(assignButton)
const metricSearchField = screen.getByRole('combobox', { name: /Select a metric/ })
const metricSearchFieldMoreButton = getByRole(metricSearchField, 'button', { name: 'Open' })
fireEvent.click(metricSearchFieldMoreButton)
fireEvent.click(await screen.findByRole('option', { name: /metric_3/ }))
const attributionWindowField = await screen.findByLabelText(/Attribution Window/)
await act(async () => {
fireEvent.focus(attributionWindowField)
})
await act(async () => {
fireEvent.keyDown(attributionWindowField, { key: 'Enter' })
})
const attributionWindowFieldOption = await screen.findByRole('option', { name: /24 hours/ })
await act(async () => {
fireEvent.click(attributionWindowFieldOption)
})
await changeFieldByRole('spinbutton', /Minimum Difference/, '1')
fireEvent.click(assignButton)
await waitForElementToBeRemoved(assignButton)
expect(mockedExperimentsApi.assignMetric).toHaveBeenCalledTimes(1)
expect(mockedExperimentsApi.assignMetric).toHaveBeenLastCalledWith(experiment, {
attributionWindowSeconds: '86400',
changeExpected: false,
isPrimary: false,
metricId: 3,
minDifference: '0.01',
})
fireEvent.click(startAssignButton)
await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
const cancelButton = screen.getByRole('button', { name: /Cancel/ })
fireEvent.click(cancelButton)
await waitForElementToBeRemoved(cancelButton)
expect(mockedExperimentsApi.assignMetric).toHaveBeenCalledTimes(1)
})
Example #23
Source File: name-collection.spec.tsx From master-frontend-lemoncode with MIT License | 5 votes |
describe('NameCollection component specs', () => {
it('should display a list with one item when it mounts the component and it resolves the async call', async () => {
// Arrange
const getStub = jest
.spyOn(api, 'getNameCollection')
.mockResolvedValue(['John Doe']);
// Act
render(<NameCollection />);
const itemsBeforeWait = screen.queryAllByRole('listitem');
expect(itemsBeforeWait).toHaveLength(0);
const items = await screen.findAllByRole('listitem');
// Assert
expect(items).toHaveLength(1);
expect(getStub).toHaveBeenCalled();
});
it('should remove initial list when it mounts the component and it resolves the async call', async () => {
// Arrange
const initialNameCollection = ['initial-user'];
const getStub = jest
.spyOn(api, 'getNameCollection')
.mockResolvedValue(['John Doe']);
// Act
render(<NameCollection initialNameCollection={initialNameCollection} />);
const initialItems = screen.getAllByRole('listitem');
expect(initialItems).toHaveLength(1);
expect(initialItems[0].textContent).toEqual('initial-user');
await waitForElementToBeRemoved(screen.queryByText('initial-user'));
// Assert
expect(screen.queryByText('initial-user')).not.toBeInTheDocument();
});
});
Example #24
Source File: SQForm.stories.test.tsx From SQForm with MIT License | 5 votes |
describe('Tests for BasicForm', () => {
it('renders BasicForm and calls alert on submit', async () => {
render(<BasicForm />);
userEvent.type(screen.getByLabelText(/first name/i), mockData.firstName);
const {value: lastNameInputValue} = screen.getByLabelText(
/last name/i
) as HTMLInputElement;
userEvent.type(screen.getByLabelText(/hobby/i), mockData.hobby);
userEvent.type(screen.getByLabelText(/age/i), mockData.age.toString());
userEvent.click(screen.getByRole('button', {name: /state/i}));
userEvent.click(screen.getByRole('option', {name: /kansas/i}));
userEvent.click(screen.getByRole('checkbox', {name: /cool/i}));
userEvent.click(
within(
screen.getByRole('group', {
name: /cat or dog/i,
})
).getByRole('radio', {name: /dog/i})
);
const warrantyOptions = screen.getByRole('group', {
name: /warranty options/i,
});
userEvent.click(
within(warrantyOptions).getByRole('checkbox', {name: /drivetrain/i})
);
userEvent.click(
within(warrantyOptions).getByRole('checkbox', {name: /brakes/i})
);
userEvent.click(screen.getByRole('button', {name: /submit/i}));
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(
JSON.stringify(
{
firstName: mockData.firstName,
lastName: lastNameInputValue,
city: '',
age: mockData.age,
state: mockData.state,
tenThousandOptions: '',
note: '',
preferredPet: mockData.preferredPet,
warrantyOptions: mockData.warrantyOptions,
warrantyOptionsSelectAll: false,
favoriteColors: [2, 4],
hobby: mockData.hobby,
cool: mockData.cool,
lame: false,
},
null,
2
)
)
);
});
it('shows confirmation and resets form', async () => {
render(<BasicForm />);
userEvent.type(screen.getByLabelText(/first name/i), mockData.firstName);
userEvent.click(screen.getByRole('button', {name: /reset/i}));
await screen.findByText('Reset Form');
userEvent.click(screen.getByRole('button', {name: /reset/i}));
await waitForElementToBeRemoved(() => screen.queryByText('Reset Form'));
const {value: firstNameInputValue} = screen.getByLabelText(
/first name/i
) as HTMLInputElement;
expect(firstNameInputValue).toBe('');
});
});
Example #25
Source File: name-collection.spec.tsx From master-frontend-lemoncode with MIT License | 5 votes |
describe('NameCollection component specs', () => {
it('should display a list with one item when it mounts the component and it resolves the async call', async () => {
// Arrange
const getStub = jest
.spyOn(api, 'getNameCollection')
.mockResolvedValue(['John Doe']);
// Act
renderWithRouter(<NameCollection />);
const itemsBeforeWait = screen.queryAllByRole('listitem');
expect(itemsBeforeWait).toHaveLength(0);
const items = await screen.findAllByRole('listitem');
// Assert
expect(items).toHaveLength(1);
expect(getStub).toHaveBeenCalled();
});
it('should remove initial list when it mounts the component and it resolves the async call', async () => {
// Arrange
const initialNameCollection = ['initial-user'];
const getStub = jest
.spyOn(api, 'getNameCollection')
.mockResolvedValue(['John Doe']);
// Act
renderWithRouter(
<NameCollection initialNameCollection={initialNameCollection} />
);
const initialItems = screen.getAllByRole('listitem');
expect(initialItems).toHaveLength(1);
expect(initialItems[0].textContent).toEqual('initial-user');
await waitForElementToBeRemoved(screen.queryByText('initial-user'));
// Assert
expect(screen.queryByText('initial-user')).not.toBeInTheDocument();
});
it('should navigate to second user edit page when click in second user name', async () => {
// Arrange
const getStub = jest
.spyOn(api, 'getNameCollection')
.mockResolvedValue(['John Doe', 'Jane Doe']);
// Act
renderWithRouter(<NameCollection />);
const links = await screen.findAllByRole('link');
const secondUser = links[1];
userEvent.click(secondUser);
const userEditElement = screen.getByRole('heading', {
name: 'User name: Jane Doe',
});
// Assert
expect(userEditElement).toBeInTheDocument();
});
});
Example #26
Source File: TranslationDashboard.test.tsx From crowdsource-dataplatform with MIT License | 4 votes |
describe('TranslationDashboard', () => {
global.document.getElementById = jest.fn().mockImplementation(
x =>
x === 'float' && {
style: {
width: '50%',
},
}
);
const fromLanguageElement = () => screen.getByRole('combobox', { name: 'Select From Language' });
const toLanguageElement = () => screen.getByRole('combobox', { name: 'Select To Language' });
const setup = async () => {
fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
JSON.stringify([
{
language: 'English-Hindi',
total_contribution_count: 36,
total_contributions: 0.057,
total_speakers: 9,
total_validation_count: 2,
total_validations: 0.001,
type: 'parallel',
},
])
);
const renderResult = render(
<SWRConfig value={{ provider: () => new Map() }}>
<TranslationDashboard />
</SWRConfig>
);
await screen.findByText('ContributionStats');
return renderResult;
};
it('should contain language selector', async () => {
await setup();
expect(fromLanguageElement()).toBeInTheDocument();
expect(toLanguageElement()).toBeInTheDocument();
expect(toLanguageElement()).toBeDisabled();
});
it('changing language in language pair selector should update stats', async () => {
await setup();
userEvent.selectOptions(fromLanguageElement(), 'English');
expect(toLanguageElement()).toBeEnabled();
userEvent.selectOptions(toLanguageElement(), 'Hindi');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing from language back to all should show all language stats', async () => {
await setup();
userEvent.selectOptions(fromLanguageElement(), 'English');
expect(toLanguageElement()).toBeEnabled();
userEvent.selectOptions(fromLanguageElement(), 'all');
expect(fromLanguageElement()).toHaveValue('all');
expect(toLanguageElement()).toHaveValue('all');
});
it('should show default languages when all languages selected in to language dropdown', async () => {
await setup();
userEvent.selectOptions(fromLanguageElement(), 'English');
userEvent.selectOptions(toLanguageElement(), 'Hindi');
userEvent.selectOptions(toLanguageElement(), 'all');
await waitFor(() => expect(fromLanguageElement()).toHaveValue('all'));
await waitFor(() => expect(toLanguageElement()).toHaveValue('all'));
});
it('changing language from language pair selector should display nodata message when data not available', async () => {
await setup();
userEvent.selectOptions(fromLanguageElement(), 'English');
userEvent.selectOptions(toLanguageElement(), 'Hindi');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
userEvent.selectOptions(toLanguageElement(), 'Bengali');
await waitFor(() => expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json'));
await waitFor(() => expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument());
await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
await setup();
userEvent.selectOptions(fromLanguageElement(), 'English');
userEvent.selectOptions(toLanguageElement(), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());
userEvent.click(screen.getByRole('button', { name: 'Close' }));
await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
});
it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
when(localStorage.getItem)
.calledWith('speakerDetails')
.mockImplementation(
() => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
);
when(localStorage.getItem)
.calledWith('contributionLanguage')
.mockImplementation(() => 'English');
when(localStorage.getItem)
.calledWith('translatedLanguage')
.mockImplementation(() => 'Hindi');
await setup();
await waitFor(() => {
expect(localStorage.getItem).toBeCalled();
});
userEvent.selectOptions(fromLanguageElement(), 'English');
userEvent.selectOptions(toLanguageElement(), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
expect(localStorage.setItem).toBeCalledWith('contributionLanguage', 'English');
expect(localStorage.setItem).toBeCalledWith('translatedLanguage', 'Bengali');
});
});
Example #27
Source File: index.tsx From exevo-pan with The Unlicense | 4 votes |
describe('<FilterDrawer />', () => {
beforeEach(() => {
jest.useFakeTimers()
jest
.spyOn(window, 'setTimeout')
.mockImplementationOnce((fn) => fn() as unknown as NodeJS.Timeout)
})
test('drawer visibility should be controlled correctly', async () => {
const { rerender } = renderWithProviders(<WrappedFilterDrawer open />)
const drawerElement = screen.getByRole('dialog')
expect(drawerElement).toBeVisible()
rerender(<WrappedFilterDrawer open={false} />)
await waitForElementToBeRemoved(drawerElement)
rerender(<WrappedFilterDrawer open />)
expect(await screen.findByRole('dialog')).toBeVisible()
})
test('should call onClose', () => {
const mockedOnClose = jest.fn()
renderWithProviders(<WrappedFilterDrawer onClose={mockedOnClose} />)
expect(mockedOnClose).toHaveBeenCalledTimes(0)
userEvent.click(screen.getByLabelText('Close drawer'))
expect(mockedOnClose).toHaveBeenCalledTimes(1)
})
test('should update filters', () => {
renderWithProviders(<WrappedFilterDrawer />)
const knightButton = screen.getByRole('switch', { name: 'Knight' })
const paladinButton = screen.getByRole('switch', { name: 'Paladin' })
expect(knightButton).not.toBeChecked()
expect(paladinButton).not.toBeChecked()
userEvent.click(knightButton)
expect(knightButton).toBeChecked()
expect(paladinButton).not.toBeChecked()
userEvent.click(paladinButton)
expect(knightButton).toBeChecked()
expect(paladinButton).toBeChecked()
const nicknameInput = screen.getByLabelText('Search nickname')
expect(nicknameInput).toHaveValue('')
userEvent.type(nicknameInput, 'Ksu')
expect(nicknameInput).toHaveValue('Ksu')
})
test('autocomplete inputs should work correctly', () => {
renderWithProviders(<WrappedFilterDrawer />)
const imbuementInput = screen.getByLabelText('Imbuements')
expect(screen.queryByText('Critical Hit')).not.toBeInTheDocument()
userEvent.click(imbuementInput)
userEvent.click(screen.getByRole('option', { name: 'Critical Hit' }))
expect(screen.queryByText('Critical Hit')).toBeInTheDocument()
userEvent.click(screen.getByLabelText('Remove item'))
expect(screen.queryByText('Critical Hit')).not.toBeInTheDocument()
userEvent.click(imbuementInput)
userEvent.click(screen.getByRole('option', { name: 'Critical Hit' }))
expect(screen.queryByText('Critical Hit')).toBeInTheDocument()
const toggleAllButton = screen.getByRole('switch', {
name: 'All imbuements',
})
userEvent.click(toggleAllButton)
imbuement.tokens.forEach((imbuementName) => {
expect(screen.queryByText(imbuementName)).toBeInTheDocument()
})
userEvent.click(toggleAllButton)
imbuement.tokens.forEach((imbuementName) => {
expect(screen.queryByText(imbuementName)).not.toBeInTheDocument()
})
userEvent.click(toggleAllButton)
imbuement.tokens.forEach((imbuementName) => {
expect(screen.queryByText(imbuementName)).toBeInTheDocument()
})
screen.getAllByLabelText('Remove item').forEach((removeButton) => {
userEvent.click(removeButton)
expect(removeButton).not.toBeInTheDocument()
})
})
test('filter reset button should work correctly', () => {
renderWithProviders(<WrappedFilterDrawer />)
expect(
screen.queryByRole('button', { name: 'Reset filters' }),
).not.toBeInTheDocument()
const knightButton = screen.getByRole('switch', { name: 'Knight' })
userEvent.click(knightButton)
const resetFilterButton = screen.getByRole('button', {
name: 'Reset filters',
})
expect(resetFilterButton).toBeEnabled()
userEvent.click(resetFilterButton)
expect(knightButton).not.toBeChecked()
expect(resetFilterButton).toBeDisabled()
userEvent.click(knightButton)
userEvent.click(
screen.getByRole('switch', {
name: 'All imbuements',
}),
)
expect(resetFilterButton).toBeEnabled()
userEvent.click(resetFilterButton)
expect(knightButton).not.toBeChecked()
imbuement.tokens.forEach((imbuementName) => {
expect(screen.queryByText(imbuementName)).not.toBeInTheDocument()
})
})
test('outfit/mount picker should work correctly', () => {
renderWithProviders(<WrappedFilterDrawer />)
outfit.tokens.forEach((outfitName) => {
expect(screen.queryByTitle(outfitName)).not.toBeInTheDocument()
})
userEvent.click(screen.getByText('Outfits'))
expect(
screen.queryByRole('button', { name: 'Reset filters' }),
).not.toBeInTheDocument()
outfit.tokens.forEach((outfitName) => {
const switchElement = screen.getByTitle(outfitName)
expect(switchElement).not.toBeChecked()
userEvent.click(switchElement)
expect(switchElement).toBeChecked()
})
const resetButton = screen.getByRole('button', { name: 'Reset filters' })
expect(resetButton).toBeEnabled()
outfit.tokens.forEach((outfitName) => {
const switchElement = screen.getByTitle(outfitName)
expect(switchElement).toBeChecked()
userEvent.click(switchElement)
expect(switchElement).not.toBeChecked()
})
expect(resetButton).toBeDisabled()
const addonElement = screen.getByRole('checkbox', { name: 'Addon 1' })
expect(addonElement).toBeChecked()
userEvent.click(addonElement)
expect(addonElement).not.toBeChecked()
expect(resetButton).toBeEnabled()
userEvent.click(resetButton)
expect(addonElement).toBeChecked()
expect(resetButton).toBeDisabled()
})
test('useDebouncedFilter should dispatch filters after a while', () => {
renderWithProviders(<WrappedFilterDrawer />)
expect(
screen.queryByRole('button', {
name: 'Reset filters',
}),
).not.toBeInTheDocument()
const nicknameInput = screen.getByLabelText('Search nickname')
expect(nicknameInput).toHaveValue('')
userEvent.type(nicknameInput, 'Ksu')
expect(nicknameInput).toHaveValue('Ksu')
expect(
screen.getByRole('button', {
name: 'Reset filters',
}),
).toBeInTheDocument()
})
})
Example #28
Source File: AsrDashboard.test.tsx From crowdsource-dataplatform with MIT License | 4 votes |
describe('AsrDashboard', () => {
global.document.getElementById = jest.fn().mockImplementation(
x =>
x === 'float' && {
style: {
width: '50%',
},
}
);
const setup = async () => {
fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
JSON.stringify([
{
language: 'English',
total_contribution_count: 36,
total_contributions: 0.057,
total_speakers: 9,
total_validation_count: 2,
total_validations: 0.001,
type: 'text',
},
])
);
const renderResult = render(
<SWRConfig value={{ provider: () => new Map() }}>
<AsrDashboard />
</SWRConfig>
);
await screen.findByText('ContributionStats');
return renderResult;
};
it('should contain language selector', async () => {
await setup();
expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
});
it('changing language from language selector should update stats', async () => {
await setup();
expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing language from language selector should display nodata message when data not available', async () => {
await setup();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
});
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
await setup();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());
userEvent.click(screen.getByRole('button', { name: 'Close' }));
await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
});
it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
when(localStorage.getItem)
.calledWith('speakerDetails')
.mockImplementation(
() => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
);
when(localStorage.getItem)
.calledWith('contributionLanguage')
.mockImplementation(() => 'English');
await setup();
await waitFor(() => {
expect(localStorage.getItem).toBeCalled();
});
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
});
});
Example #29
Source File: OcrDashboard.test.tsx From crowdsource-dataplatform with MIT License | 4 votes |
describe('OcrDashboard', () => {
global.document.getElementById = jest.fn().mockImplementation(
x =>
x === 'float' && {
style: {
width: '50%',
},
}
);
const setup = async () => {
fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
JSON.stringify([
{
language: 'English',
total_contribution_count: 36,
total_contributions: 0.057,
total_speakers: 9,
total_validation_count: 2,
total_validations: 0.001,
type: 'ocr',
},
])
);
const renderResult = render(
<SWRConfig value={{ provider: () => new Map() }}>
<OcrDashboard />
</SWRConfig>
);
await screen.findByText('ContributionStats');
return renderResult;
};
it('should contain language selector', async () => {
await setup();
expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
});
it('changing language from language selector should update stats', async () => {
await setup();
expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing language from language selector should display nodata message when data not available', async () => {
await setup();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
});
await waitFor(async () => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
expect(screen.queryByText('languages')).not.toBeInTheDocument();
});
it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
await setup();
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());
userEvent.click(screen.getByRole('button', { name: 'Close' }));
await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
});
it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
when(localStorage.getItem)
.calledWith('speakerDetails')
.mockImplementation(
() => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
);
when(localStorage.getItem)
.calledWith('contributionLanguage')
.mockImplementation(() => 'English');
await setup();
await waitFor(() => {
expect(localStorage.getItem).toBeCalled();
});
userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
await waitFor(() => {
expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
});
userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
});
});