@testing-library/react#getAllByRole JavaScript Examples
The following examples show how to use
@testing-library/react#getAllByRole.
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: setup.js From ui-data-export with Apache License 2.0 | 5 votes |
transformationListRows = () => getAllByRole(screen.getByRole('rowgroup'), 'row')
Example #2
Source File: setup.js From ui-data-export with Apache License 2.0 | 5 votes |
columnHeaderFieldName = () => screen.getAllByRole('columnheader', { name: translations['mappingProfiles.transformations.fieldName'] })
Example #3
Source File: setup.js From ui-data-export with Apache License 2.0 | 5 votes |
columnHeaderTransformation = () => screen.getAllByRole('columnheader', { name: translations['mappingProfiles.transformations.transformation'] })
Example #4
Source File: BbbSettings.test.jsx From frontend-app-course-authoring with GNU Affero General Public License v3.0 | 5 votes |
describe('BBB Settings', () => {
beforeEach(async () => {
initializeMockApp({
authenticatedUser: {
userId: 3,
username: 'abc123',
administrator: false,
roles: [],
},
});
store = initializeStore(initialState);
axiosMock = new MockAdapter(getAuthenticatedHttpClient());
history.push(liveSettingsUrl);
});
test('Plan dropdown to be visible and enabled in UI', async () => {
await mockStore({ emailSharing: true });
renderComponent();
const spinner = getByRole(container, 'status');
await waitForElementToBeRemoved(spinner);
expect(queryByTestId(container, 'plansDropDown')).toBeInTheDocument();
expect(container.querySelector('select[name="tierType"]')).not.toBeDisabled();
});
it('Plan dropdown should display correct number of options', async () => {
await mockStore({ emailSharing: true });
renderComponent();
const spinner = getByRole(container, 'status');
await waitForElementToBeRemoved(spinner);
const dropDown = queryByTestId(container, 'plansDropDown');
expect(getAllByRole(dropDown, 'option').length).toBe(3);
});
test('Connect to support and PII sharing message is visible and plans selection is disabled, When pii sharing is disabled, ',
async () => {
await mockStore({ piiSharingAllowed: false });
renderComponent();
const spinner = getByRole(container, 'status');
await waitForElementToBeRemoved(spinner);
const requestPiiText = queryByTestId(container, 'request-pii-sharing');
const helpRequestPiiText = queryByTestId(container, 'help-request-pii-sharing');
expect(requestPiiText).toHaveTextContent(
messages.requestPiiSharingEnableForBbb.defaultMessage.replaceAll('{provider}', 'BigBlueButton'),
);
expect(helpRequestPiiText).toHaveTextContent(messages.piiSharingEnableHelpTextBbb.defaultMessage);
expect(container.querySelector('select[name="tierType"]')).toBeDisabled();
});
test('free plans message is visible when free plan is selected', async () => {
await mockStore({ emailSharing: true, isFreeTier: true });
renderComponent();
const spinner = getByRole(container, 'status');
await waitForElementToBeRemoved(spinner);
const dropDown = container.querySelector('select[name="tierType"]');
userEvent.selectOptions(
dropDown,
getByRole(dropDown, 'option', { name: 'Free' }),
);
expect(queryByTestId(container, 'free-plan-message')).toBeInTheDocument();
expect(queryByTestId(container, 'free-plan-message')).toHaveTextContent(messages.freePlanMessage.defaultMessage);
});
});
Example #5
Source File: index.jsdom.test.jsx From apps-todo-list with MIT License | 4 votes |
describe('TodoApp', () => {
let mutations;
let addMutation = mutation => mutations.push(mutation);
let testDriver;
beforeEach(() => {
testDriver = new TestDriver(recordListFixture);
mutations = [];
testDriver.watch('mutation', addMutation);
render(
<testDriver.Container>
<TodoApp />
</testDriver.Container>,
);
});
afterEach(() => {
testDriver.unwatch('mutations', addMutation);
});
it('renders a list of records (user with "write" permissions)', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
const items = readItems();
expect(items.length).toBe(3);
expect(items).toEqual([
{checked: false, text: 'carrots'},
{checked: true, text: 'baby carrots'},
{checked: false, text: 'elderly carrots'},
]);
});
// This test cannot be fully expressed using the capabilities currently
// available in the SDK.
it('renders a list of records (user without "write" permissions)', async () => {
testDriver.simulatePermissionCheck(mutation => {
return mutation.type === 'setMultipleGlobalConfigPaths';
});
await openAsync('Groceries', 'Grid view', 'Purchased');
expect(screen.getByRole('button', {name: 'Add'}).disabled).toBe(true);
const items = getItems().map(item => ({
checked: item.checkbox.checked,
text: item.container.textContent.trim(),
checkboxDisabled: item.checkbox.disabled,
deleteButtonDisabled: item.deleteButton.disabled,
}));
expect(items.length).toBe(3);
expect(items).toEqual([
{checked: false, text: 'carrots', checkboxDisabled: true, deleteButtonDisabled: true},
{
checked: true,
text: 'baby carrots',
checkboxDisabled: true,
deleteButtonDisabled: true,
},
{
checked: false,
text: 'elderly carrots',
checkboxDisabled: true,
deleteButtonDisabled: true,
},
]);
});
it('gracefully handles the deletion of fields', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
await act(() => testDriver.deleteFieldAsync('tblTable1', 'fldPurchased'));
const items = readItems();
expect(items).toEqual([]);
});
it('gracefully handles the deletion of tables', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
act(() => {
testDriver.deleteTable('tblTable1');
});
const items = readItems();
expect(items).toEqual([]);
const options = getAllByRole(screen.getByLabelText('Table'), 'option');
expect(options.map(getNodeText)).toEqual(['Pick a table...', 'Porcelain dolls']);
expect(options[0].selected).toBe(true);
expect(screen.queryByLabelText('View')).toBe(null);
expect(screen.queryByLabelText('Field')).toBe(null);
});
it('gracefully handles the deletion of views', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
await act(() => testDriver.deleteViewAsync('tblTable1', 'viwGridView'));
const items = readItems();
expect(items).toEqual([]);
const tableOptions = getAllByRole(screen.getByLabelText('Table'), 'option');
expect(tableOptions.map(getNodeText)).toEqual([
'Pick a table...',
'Groceries',
'Porcelain dolls',
]);
expect(tableOptions[1].selected).toBe(true);
const viewOptions = getAllByRole(screen.getByLabelText('View'), 'option');
expect(viewOptions.map(getNodeText)).toEqual(['Pick a view...', 'Another grid view']);
expect(viewOptions[0].selected).toBe(true);
const fieldOptions = getAllByRole(screen.getByLabelText('Field'), 'option');
expect(fieldOptions.map(getNodeText)).toEqual([
"Pick a 'done' field...",
'Name',
'Purchased',
]);
expect(fieldOptions[2].selected).toBe(true);
});
it('allows records to be created without a name', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
const initialCount = readItems().length;
userEvent.click(screen.getByRole('button', {name: 'Add'}));
const items = readItems();
expect(items.length).toBe(initialCount + 1);
expect(items.pop()).toEqual({
checked: false,
text: 'Unnamed record',
});
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'createMultipleRecords',
tableId: 'tblTable1',
records: [
{
id: expect.anything(),
cellValuesByFieldId: {
fldName: '',
},
},
],
},
]),
);
});
it('allows multiple records to be created with a name', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
const initialCount = readItems().length;
userEvent.type(screen.getByRole('textbox'), 'brash teenaged carrots');
userEvent.click(screen.getByRole('button', {name: 'Add'}));
let items = readItems();
expect(items.length).toBe(initialCount + 1);
expect(items.pop()).toEqual({
checked: false,
text: 'brash teenaged carrots',
});
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'createMultipleRecords',
tableId: 'tblTable1',
records: [
{
id: expect.anything(),
cellValuesByFieldId: {
fldName: 'brash teenaged carrots',
},
},
],
},
]),
);
mutations.length = 0;
userEvent.type(screen.getByRole('textbox'), 'parsnips');
userEvent.click(screen.getByRole('button', {name: 'Add'}));
items = readItems();
expect(items.length).toBe(initialCount + 2);
expect(items.pop()).toEqual({
checked: false,
text: 'parsnips',
});
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'createMultipleRecords',
tableId: 'tblTable1',
records: [
{
id: expect.anything(),
cellValuesByFieldId: {
fldName: 'parsnips',
},
},
],
},
]),
);
});
it('allows records to be destroyed', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
userEvent.click(getItems()[1].deleteButton);
const items = readItems();
expect(items).toEqual([
{checked: false, text: 'carrots'},
{checked: false, text: 'elderly carrots'},
]);
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'deleteMultipleRecords',
tableId: 'tblTable1',
recordIds: ['recb'],
},
]),
);
});
it('allows records to be marked as "complete"', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
userEvent.click(getItems()[0].checkbox);
const items = readItems();
expect(items[0]).toEqual({checked: true, text: 'carrots'});
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'setMultipleRecordsCellValues',
tableId: 'tblTable1',
records: [
{
id: 'reca',
cellValuesByFieldId: {
fldPurchased: true,
},
},
],
},
]),
);
});
it('allows records to be marked as "incomplete"', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
userEvent.click(getItems()[1].checkbox);
const items = readItems();
expect(items[1]).toEqual({checked: false, text: 'baby carrots'});
await waitFor(() => expect(mutations.length).not.toBe(0));
expect(mutations).toEqual(
expect.arrayContaining([
{
type: 'setMultipleRecordsCellValues',
tableId: 'tblTable1',
records: [
{
id: 'recb',
cellValuesByFieldId: {
fldPurchased: false,
},
},
],
},
]),
);
});
it('expands records upon click', async () => {
await openAsync('Groceries', 'Grid view', 'Purchased');
const recordIds = [];
testDriver.watch('expandRecord', ({recordId}) => recordIds.push(recordId));
userEvent.click(getItems()[0].link);
await waitFor(() => expect(recordIds.length).not.toBe(0));
expect(recordIds).toEqual(['reca']);
});
});
Example #6
Source File: MappingProfileDetails.test.js From ui-data-export with Apache License 2.0 | 4 votes |
describe('MappingProfileDetails', () => {
describe('rendering details for a mapping profile which is already in use', () => {
const renderMappingProfileDetails = () => renderWithIntl(
<MappingProfileDetailsContainer
allTransformations={allMappingProfilesTransformations}
isDefaultProfile
isProfileUsed
/>,
translationsProperties
);
it('should display mapping profile details', () => {
renderMappingProfileDetails();
const dialog = screen.getByRole('dialog');
expect(dialog).toBeVisible();
const headings = within(dialog).getAllByRole('heading', { name: mappingProfileWithTransformations.name });
headings.forEach(heading => expect(heading).toBeVisible());
expect(within(dialog).getByRole('button', { name: /collapse all/i })).toBeVisible();
const summary = within(dialog).getByRole('region', { name: /summary/i });
const transformations = within(dialog).getByRole('region', { name: /transformations/i });
expect(summary).toBeVisible();
expect(transformations).toBeVisible();
const labelsAndValues = [
'Record created: 12/4/2018 1:29 AM',
'Record last updated: 12/4/2018 1:29 AM',
commonTranslations.name,
'AP Holdings 1',
translations.description,
'AP Holdings 1 description',
translations.outputFormat,
'MARC',
commonTranslations.folioRecordType,
commonTranslations['recordTypes.holdings'],
];
labelsAndValues.forEach(el => expect(within(summary).getByText(el)).toBeVisible());
});
it('should display correct transformations fields headers', () => {
renderMappingProfileDetails();
expect(screen.getByRole('columnheader', { name: translations['mappingProfiles.transformations.fieldName'] })).toBeVisible();
expect(screen.getByRole('columnheader', { name: translations['mappingProfiles.transformations.transformation'] })).toBeVisible();
});
it('should display correct transformations values', () => {
renderMappingProfileDetails();
const transformationListRows = getAllByRole(screen.getByRole('rowgroup'), 'row');
expect(getByText(transformationListRows[0], 'Holdings - Call number - Call number')).toBeVisible();
expect(getByText(transformationListRows[0], '11100$a')).toBeVisible();
expect(getByText(transformationListRows[1], 'Holdings - Notes - Action note')).toBeVisible();
expect(getByText(transformationListRows[1], '123 1$12')).toBeVisible();
});
it('should display action buttons in the proper state', () => {
const { container } = renderMappingProfileDetails();
const actionButton = container.querySelector('[data-test-pane-header-actions-button]');
const disableButton = container.querySelector('[data-test-delete-profile-button]');
const duplicateButton = container.querySelector('[data-test-duplicate-profile-button]');
const deleteButton = container.querySelector('[data-test-delete-profile-button]');
userEvent.click(actionButton);
expect(disableButton).toBeDisabled();
expect(duplicateButton).toBeEnabled();
expect(deleteButton).toBeDisabled();
});
});
describe('rendering details for a mapping profile which is already in use', () => {
const renderMappingProfileDetailsWithMapping = () => renderWithIntl(
<MappingProfileDetailsContainer mappingProfile={mappingProfileWithoutTransformations} />,
translationsProperties
);
it('should display no value in description', () => {
const { container } = renderMappingProfileDetailsWithMapping();
const summaryDescriptionValue = container.querySelector('[data-test-mapping-profile-description]');
expect(getByText(summaryDescriptionValue, '-')).toBeVisible();
});
it('should not display delete confirmation modal', () => {
const { container } = renderMappingProfileDetailsWithMapping();
const deleteConfirmationModal = container.querySelector('#delete-mapping-profile-confirmation-modal');
expect(deleteConfirmationModal).not.toBeInTheDocument();
});
it('should not display transformation list', () => {
const { container } = renderMappingProfileDetailsWithMapping();
const transformationList = container.querySelector('#mapping-profile-transformations-list');
expect(transformationList).not.toBeInTheDocument();
});
it('should display action buttons enabled', () => {
const { container } = renderMappingProfileDetailsWithMapping();
const actionButton = container.querySelector('[data-test-pane-header-actions-button]');
const disableButton = container.querySelector('[data-test-delete-profile-button]');
const duplicateButton = container.querySelector('[data-test-duplicate-profile-button]');
const deleteButton = container.querySelector('[data-test-delete-profile-button]');
userEvent.click(actionButton);
expect(disableButton).toBeEnabled();
expect(duplicateButton).toBeEnabled();
expect(deleteButton).toBeEnabled();
});
describe('clicking on delete profiles button', () => {
it('should display delete confirmation modal', async () => {
renderMappingProfileDetailsWithMapping();
const actionButton = document.querySelector('[data-test-pane-header-actions-button]');
userEvent.click(actionButton);
const deleteButton = document.querySelector('[data-test-delete-profile-button]');
userEvent.click(deleteButton);
const modal = screen.getAllByRole('dialog').find(dialog => within(dialog).getByRole('heading', { name: /delete/i }));
expect(modal).toBeVisible();
userEvent.click(within(modal).getByRole('button', { name: /cancel/i }));
await waitForElementToBeRemoved(modal);
});
});
});
describe('rendering mapping profile details in loading state', () => {
it('should display preloader', () => {
const { container } = renderWithIntl(<MappingProfileDetailsContainer
mappingProfile={mappingProfileWithoutTransformations}
isLoading
isProfileUsed
/>,
translationsProperties);
expect(container.querySelector('[data-test-preloader]')).toBeVisible();
});
});
});
Example #7
Source File: MappingProfilesFormContainer.test.js From ui-data-export with Apache License 2.0 | 4 votes |
describe('MappingProfileFormContainer', () => {
describe('rendering MappingProfileForm', () => {
const onSubmitMock = jest.fn();
beforeEach(() => {
renderWithIntl(
<MappingProfileFormContainer
allTransformations={allMappingProfilesTransformations}
onSubmit={onSubmitMock}
/>,
translationsProperties
);
});
it('should place accordion headers in correct order', () => {
const headers = document.querySelectorAll('[data-test-headline]');
expect(getByText(headers[0], 'Summary')).toBeVisible();
expect(getByText(headers[1], 'Transformations')).toBeVisible();
});
it('should place summary fields in correct order', () => {
const labels = document.querySelectorAll('[data-test-accordion-section] label');
expect(getByText(labels[0], 'Name')).toBeVisible();
expect(getByText(labels[1], 'Output format')).toBeVisible();
expect(getByText(labels[2], 'FOLIO record type')).toBeVisible();
expect(getByText(labels[3], 'Source record storage (entire record)')).toBeVisible();
expect(getByText(labels[4], 'Inventory instance (selected fields)')).toBeVisible();
expect(getByText(labels[5], 'Holdings')).toBeVisible();
expect(getByText(labels[6], 'Item')).toBeVisible();
expect(getByText(labels[7], 'Description')).toBeVisible();
});
it('should disable instance record type option when selecting SRS', () => {
userEvent.click(screen.getByRole('checkbox', { name: 'Source record storage (entire record)' }));
expect(screen.getByDisplayValue('INSTANCE')).toBeDisabled();
});
it('should disable instance record type option in transformation list when selecting SRS', () => {
userEvent.click(screen.getByRole('checkbox', { name: 'Source record storage (entire record)' }));
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
const modalRecordFilters = screen.getByRole('region', { name: 'Record type filter list' });
expect(getByRole(modalRecordFilters, 'checkbox', { name: 'Instance' })).toBeDisabled();
});
it('should disable SRS record type option when selecting instance', () => {
userEvent.click(screen.getByRole('checkbox', { name: 'Inventory instance (selected fields)' }));
expect(screen.getByRole('checkbox', { name: 'Source record storage (entire record)' })).toBeDisabled();
});
it('should close transformations modal when clicking on cancel button', () => {
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
const modal = document.querySelector('.modalRoot');
userEvent.click(getByRole(modal, 'button', { name: 'Cancel' }));
return waitForElementToBeRemoved(() => document.querySelector('.modalRoot'));
});
it('should display validation error when record type is not selected', () => {
userEvent.click(screen.getByRole('checkbox', { name: 'Item' }));
userEvent.click(screen.getByRole('checkbox', { name: 'Item' }));
expect(getByText(document.querySelector('[data-test-folio-record-type]'),
'Please enter a value')).toBeVisible();
});
it('should display correct pane title', () => {
expect(getByText(document.querySelector('[data-test-pane-header]'), 'New field mapping profile')).toBeVisible();
});
it('should not display empty transformation fields', () => {
expect(screen.getByText('No transformations found')).toBeVisible();
});
it('should disable save button if there are no changes', () => {
expect(screen.getByRole('button', { name: 'Save & close' })).toBeDisabled();
});
it('should not mark fields as error by default', () => {
expect(document.querySelector('[data-test-folio-record-type-error]').childElementCount).toBe(0);
expect(screen.getByLabelText('Name*').parentElement.classList.contains('hasError')).toBeFalsy();
});
describe('changing transformation field value', () => {
let transformationFields;
let modal;
let transformationListRows;
let footer;
let formSubmitButton;
beforeEach(() => {
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
userEvent.click(screen.getByLabelText('Select all fields'));
transformationFields = getTransformationFieldGroups();
modal = document.querySelector('.modalRoot');
userEvent.type(transformationFields[0].marcField.input, '123');
userEvent.type(transformationFields[0].indicator1.input, '1');
userEvent.type(transformationFields[0].indicator2.input, '0');
userEvent.type(transformationFields[0].subfield.input, '$r');
userEvent.type(transformationFields[1].marcField.input, '900');
userEvent.type(transformationFields[1].subfield.input, '$1');
userEvent.click(getByRole(modal, 'button', { name: 'Save & close' }));
transformationListRows = getAllByRole(screen.getByRole('rowgroup'), 'row');
footer = document.querySelector('[data-test-pane-footer-end]');
formSubmitButton = getByRole(footer, 'button', { name: 'Save & close' });
});
it('should select all and add transformations with values', () => {
expect(transformationListRows.length).toBe(2);
expect(getByText(transformationListRows[0], '12310$r')).toBeVisible();
expect(getByText(transformationListRows[1], '900 $1')).toBeVisible();
});
it('should enable submit button', () => {
expect(formSubmitButton).not.toBeDisabled();
});
it('should display validation error when transformations do not match record type', () => {
const folioRecordTypeContainer = document.querySelector('[data-test-folio-record-type]');
userEvent.type(screen.getByLabelText('Name*'), 'Name');
userEvent.click(getByRole(folioRecordTypeContainer, 'checkbox', { name: 'Item' }));
userEvent.click(getByRole(footer, 'button', { name: 'Save & close' }));
expect(getByText(document.querySelector('[data-test-folio-record-type]'),
'Selected record types do not match specified transformations')).toBeVisible();
});
it('should disable submit button after clearing transformations', () => {
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
userEvent.click(screen.getByLabelText('Select all fields'));
userEvent.click(getByRole(modal, 'button', { name: 'Save & close' }));
expect(formSubmitButton).toBeDisabled();
});
it('should not display validation for record types when SRS and holdings types are checked', () => {
const folioRecordTypeContainer = document.querySelector('[data-test-folio-record-type]');
userEvent.type(screen.getByLabelText('Name*'), 'Name');
userEvent.click(getByRole(folioRecordTypeContainer, 'checkbox', { name: 'Holdings' }));
userEvent.click(screen.getByRole('checkbox', { name: 'Source record storage (entire record)' }));
userEvent.click(getByRole(footer, 'button', { name: 'Save & close' }));
expect(queryByText(document.querySelector('[data-test-folio-record-type]'),
'Selected record types do not match specified transformations')).toBeNull();
expect(onSubmitMock).toBeCalled();
});
describe('reopening transformation modal', () => {
beforeEach(async () => {
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
});
it('should display proper amount of found transformations', () => {
const modalHeader = document.querySelector('[data-test-pane-header-sub]');
expect(getByText(modalHeader, '2 fields found')).toBeVisible();
});
it('should display proper total selected count', () => {
const totalSelected = document.querySelector('[data-test-transformations-total-selected]');
expect(getByText(totalSelected, 'Total selected: 2')).toBeVisible();
});
it('should have correct placeholders', () => {
expect(transformationFields.length).toEqual(2);
expect(queryByPlaceholderText(transformationFields[1].marcField.container, '900')).toBeNull();
expect(queryByPlaceholderText(transformationFields[1].indicator1.container, '0')).toBeNull();
expect(queryByPlaceholderText(transformationFields[1].indicator2.container, '0')).toBeNull();
expect(queryByPlaceholderText(transformationFields[1].subfield.container, '$a')).toBeNull();
});
it('should have correct placeholders after the first transformation is selected and hidden after the selected items filter is unchecked', () => {
userEvent.click(screen.getAllByRole('checkbox', { name: 'Select field' })[0]);
userEvent.click(screen.getByRole('checkbox', { name: 'Selected' }));
transformationFields = getTransformationFieldGroups();
expect(transformationFields.length).toEqual(1);
expect(queryByPlaceholderText(transformationFields[0].marcField.container, '900')).toBeNull();
expect(queryByPlaceholderText(transformationFields[0].indicator1.container, '0')).toBeNull();
expect(queryByPlaceholderText(transformationFields[0].indicator2.container, '0')).toBeNull();
expect(queryByPlaceholderText(transformationFields[0].subfield.container, '$a')).toBeNull();
});
it('should display correct transformation fields values', () => {
expect(transformationFields[0].marcField.input.value).toBe('123');
expect(transformationFields[0].indicator1.input.value).toBe('1');
expect(transformationFields[0].indicator2.input.value).toBe('0');
expect(transformationFields[0].subfield.input.value).toBe('$r');
expect(transformationFields[1].marcField.input.value).toBe('900');
expect(transformationFields[1].indicator1.input.value).toBe('');
expect(transformationFields[1].indicator2.input.value).toBe('');
expect(transformationFields[1].indicator2.input.value).toBe('');
expect(transformationFields[1].subfield.input.value).toBe('$1');
});
describe('unchecking transformation, clicking cancel and reopening modal', () => {
it('should display correct selected field count', () => {
const selectTransformationCheckboxes = screen.getAllByLabelText('Select field');
userEvent.click(selectTransformationCheckboxes[0]);
userEvent.click(getByRole(modal, 'button', { name: 'Cancel' }));
userEvent.click(screen.getByRole('button', { name: 'Add transformations' }));
const totalSelected = document.querySelector('[data-test-transformations-total-selected]');
expect(getByText(totalSelected, 'Total selected: 2')).toBeVisible();
});
});
});
});
});
});
Example #8
Source File: MappingProfilesTransformationsModal.test.js From ui-data-export with Apache License 2.0 | 4 votes |
describe('MappingProfilesTransformationsModal', () => {
describe('rendering mapping profile transformations modal', () => {
const onSubmitMock = jest.fn();
let modal;
beforeEach(() => {
renderWithIntl(
<MappingProfilesTransformationModalContainer
onSubmit={onSubmitMock}
/>,
translationsProperties
);
modal = document.querySelector('[data-test-transformations-modal]');
});
afterEach(() => {
jest.clearAllMocks();
});
it('should display transformations modal', () => {
expect(modal).toBeInTheDocument();
});
it('should display search pane', () => {
expect(modal.querySelector('[data-test-transformations-search-pane]')).toBeInTheDocument();
});
it('should display results pane', () => {
const resultsPane = modal.querySelector('[data-test-transformations-results-pane]');
expect(resultsPane).toBeInTheDocument();
expect(getByText(resultsPane, 'Transformations')).toBeInTheDocument();
expect(getByText(resultsPane, `${initialValues.transformations.length} fields found`)).toBeInTheDocument();
});
it('should display total selected count', () => {
expect(getByText(modal, 'Total selected: 0')).toBeInTheDocument();
});
it('should display search form', () => {
expect(modal.querySelector('[data-test-transformations-search-form]')).toBeInTheDocument();
});
it('should display correct folio record types', () => {
const checkboxes = getAllByRole(modal, 'checkbox');
expect(checkboxes[0].value).toBe('INSTANCE');
expect(checkboxes[1].value).toBe('HOLDINGS');
expect(checkboxes[2].value).toBe('ITEM');
});
it('should display cancel button', () => {
expect(getByRole(modal, 'button', { name: 'Cancel' })).toBeInTheDocument();
});
it('should display save button', () => {
expect(getByRole(modal, 'button', { name: 'Save & close' })).toBeInTheDocument();
});
describe('filling transformation values', () => {
let transformationFields;
let submitButton;
beforeEach(() => {
transformationFields = getTransformationFieldGroups();
submitButton = getByRole(modal, 'button', { name: 'Save & close' });
userEvent.type(transformationFields[0].marcField.input, '123');
userEvent.type(transformationFields[0].indicator1.input, '1');
userEvent.type(transformationFields[0].indicator2.input, '0');
userEvent.type(transformationFields[0].subfield.input, '$r');
});
it('should enable submit button', () => {
expect(submitButton).not.toBeDisabled();
});
it('should validate fields as valid and initiate modal submit', () => {
userEvent.click(submitButton);
expect(onSubmitMock).toBeCalled();
});
describe('selecting all fields and clicking submit', () => {
beforeEach(() => {
userEvent.click(screen.getByLabelText('Select all fields'));
userEvent.click(submitButton);
transformationFields = getTransformationFieldGroups();
});
it('should not initiate modal submit', () => {
expect(onSubmitMock).not.toBeCalled();
});
it('should disable submit button', () => {
expect(submitButton).toBeDisabled();
});
it('should validate instance record type transformation as valid (instances can be empty)', () => {
expect(transformationFields[1].isInvalid).toBe(false);
});
it('should validate item record type transformation and mark marcField as invalid', () => {
expect(transformationFields[2].isInvalid).toBe(true);
expect(transformationFields[2].marcField.isInvalid).toBe(true);
expect(transformationFields[2].indicator1.isInvalid).toBe(false);
expect(transformationFields[2].indicator2.isInvalid).toBe(false);
expect(transformationFields[2].subfield.isInvalid).toBe(false);
});
describe('filling empty invalid field with invalid transformation', () => {
beforeEach(() => {
userEvent.type(transformationFields[2].subfield.input, '12');
userEvent.click(submitButton);
transformationFields = getTransformationFieldGroups();
});
it('should mark transformation field group, marc field and subfield as invalid', () => {
expect(transformationFields[2].isInvalid).toBe(true);
expect(transformationFields[2].marcField.isInvalid).toBe(true);
expect(transformationFields[2].indicator1.isInvalid).toBe(false);
expect(transformationFields[2].indicator2.isInvalid).toBe(false);
expect(transformationFields[2].subfield.isInvalid).toBe(true);
});
describe('changing marc field', () => {
beforeEach(() => {
userEvent.type(transformationFields[2].marcField.input, '900');
transformationFields = getTransformationFieldGroups();
});
it('should mark marc field as valid and keep subfield and transformation group as invalid', () => {
expect(transformationFields[2].isInvalid).toBe(true);
expect(transformationFields[2].marcField.isInvalid).toBe(false);
expect(transformationFields[2].subfield.isInvalid).toBe(true);
});
it('should mark subfield as valid as well as transformation group after addressing every invalid field', () => {
userEvent.type(transformationFields[2].subfield.input, '$12');
transformationFields = getTransformationFieldGroups();
expect(transformationFields[2].isInvalid).toBe(false);
expect(transformationFields[2].subfield.isInvalid).toBe(false);
});
});
});
describe('filling empty invalid field with valid transformation', () => {
beforeEach(() => {
userEvent.type(transformationFields[2].marcField.input, '900');
userEvent.type(transformationFields[2].indicator1.input, 'r');
userEvent.type(transformationFields[2].indicator2.input, '1');
userEvent.type(transformationFields[2].subfield.input, '$90');
userEvent.click(submitButton);
});
it('should validate fields as valid and initiate modal submit', () => {
transformationFields = getTransformationFieldGroups();
expect(transformationFields[2].marcField.isInvalid).toBe(false);
expect(transformationFields[2].indicator1.isInvalid).toBe(false);
expect(transformationFields[2].indicator2.isInvalid).toBe(false);
expect(transformationFields[2].subfield.isInvalid).toBe(false);
expect(onSubmitMock).toBeCalledWith([{
enabled: true,
fieldId: 'field1',
rawTransformation: {
marcField: '123',
indicator1: '1',
indicator2: '0',
subfield: '$r',
},
recordType: 'HOLDINGS',
transformation: '12310$r',
}, {
enabled: true,
fieldId: 'field2',
recordType: 'INSTANCE',
transformation: '',
}, {
enabled: true,
fieldId: 'field3',
rawTransformation: {
marcField: '900',
indicator1: 'r',
indicator2: '1',
subfield: '$90',
},
recordType: 'ITEM',
transformation: '900r1$90',
}]);
});
});
});
});
});
});