diff --git a/src/account-settings/AccountSettingsPage.jsx b/src/account-settings/AccountSettingsPage.jsx index 8a6e54d05..a391c461d 100644 --- a/src/account-settings/AccountSettingsPage.jsx +++ b/src/account-settings/AccountSettingsPage.jsx @@ -52,6 +52,7 @@ import { fetchSiteLanguages } from './site-language'; import DemographicsSection from './demographics/DemographicsSection'; import { fetchCourseList } from '../notification-preferences/data/thunks'; import { withLocation, withNavigate } from './hoc'; +import NameField from './NameField'; class AccountSettingsPage extends React.Component { constructor(props, context) { @@ -167,6 +168,34 @@ class AccountSettingsPage extends React.Component { this.props.saveSettings(formId, values, extendedProfileObject); }; + handleSubmitFirstAndLastName = (formId, fullName, firstName, lastName) => { + const settingsToBeSaved = []; + + if (Object.keys(this.props.drafts).includes('useVerifiedNameForCerts')) { + settingsToBeSaved.push({ + formId: 'useVerifiedNameForCerts', + commitValues: this.props.formValues.useVerifiedNameForCerts, + }); + } + + settingsToBeSaved.push({ + formId: 'first_name', + commitValues: firstName, + }); + + settingsToBeSaved.push({ + formId: 'last_name', + commitValues: lastName, + }); + + settingsToBeSaved.push({ + formId: 'name', + commitValues: fullName, + }); + + this.props.saveMultipleSettings(settingsToBeSaved, formId, false); + }; + handleSubmitProfileName = (formId, values) => { if (Object.keys(this.props.drafts).includes('useVerifiedNameForCerts')) { this.props.saveMultipleSettings([ @@ -552,37 +581,71 @@ class AccountSettingsPage extends React.Component { isEditable={false} {...editableFieldProps} /> - + ) : ( + + onChange={this.handleEditableFieldChange} + onSubmit={this.handleSubmitProfileName} + /> + )} + {verifiedName && ( { + const { + name, + label, + emptyLabel, + type, + fullNameValue, + firstNameValue, + lastNameValue, + verifiedName, + pendingNameChange, + userSuppliedValue, + saveState, + error, + firstNameError, + lastNameError, + confirmationMessageDefinition, + confirmationValue, + helpText, + onEdit, + onCancel, + onSubmit, + onChange, + isEditing, + isEditable, + isGrayedOut, + intl, + ...others + } = props; + + const id = `field-${name}`; + + const firstNameFieldAttributes = { + name: 'first_name', + id: 'field-firstName', + label: intl.formatMessage(messages['account.settings.field.first.name']), + }; + + const lastNameFieldAttributes = { + name: 'last_name', + id: 'field-lastName', + label: intl.formatMessage(messages['account.settings.field.last.name']), + }; + + const [fullName, setFullName] = useState(''); + const [firstName, setFirstName] = useState(''); + const [lastName, setLastName] = useState(''); + const [fieldError, setFieldError] = useState(''); + + /** + * Concatenates first and last name and generates full name. + * @param first + * @param last + * @returns {`${string} ${string}`} + */ + const generateFullName = (first, last) => { + if (first && last) { + return `${first} ${last}`; + } + return first || last; + }; + + /** + * Splits a full name into first name and last name such that the first word + * is the firstName and rest of the name is last name. + * - If the full name is "John Doe Hamilton", the splitting will be + * e.g., fullName = John Doe => firstName = John, lastName = Doe Hamilton + * @param {string} nameValue The full name to split. + * @returns {object} An object containing the firstName and lastName. + */ + const splitFullName = (nameValue) => { + const [first, ...lastNameArr] = nameValue.trim().split(' '); + const last = lastNameArr.join(' '); + return { first, last }; + }; + + /** + * UseEffect for setting first and last name. + */ + useEffect(() => { + if (firstNameValue || lastNameValue) { + setFirstName(firstNameValue); + setLastName(lastNameValue); + } else { + const { first, last } = splitFullName(fullNameValue); + setFirstName(first); + setLastName(last); + } + }, [firstNameValue, fullNameValue, lastNameValue]); + + /** + * UseEffect for setting full name. + */ + useEffect(() => { + if (verifiedName?.status === 'submitted' && pendingNameChange) { + setFullName(pendingNameChange); + } else if (firstNameValue || lastNameValue) { + setFullName(generateFullName(firstNameValue, lastNameValue)); + } else { + setFullName(fullNameValue); + } + }, [firstNameValue, fullNameValue, lastNameValue, pendingNameChange, verifiedName?.status]); + + /** + * UseEffect for setting error + */ + useEffect(() => { + setFieldError(error || firstNameError || lastNameError); + }, [error, firstNameError, lastNameError]); + + const handleSubmit = (e) => { + e.preventDefault(); + const formData = new FormData(e.target); + const firstNameVal = formData.get(firstNameFieldAttributes.name).trim(); + const lastNameVal = formData.get(lastNameFieldAttributes.name).trim(); + const fullNameVal = generateFullName(firstName, lastName); + + onSubmit(name, fullNameVal, firstNameVal, lastNameVal); + }; + + const handleChange = (e, fieldName) => { + onChange(fieldName, e.target.value); + // Updating full name along with the updates to first and last name + if (fieldName === firstNameFieldAttributes.name) { + onChange(name, generateFullName(e.target.value.trim(), lastNameValue)); + } else if (fieldName === lastNameFieldAttributes.name) { + onChange(name, generateFullName(firstNameValue, e.target.value.trim())); + } + }; + + const handleEdit = () => { + onEdit(name); + }; + + const handleCancel = () => { + onCancel(name); + }; + + const renderEmptyLabel = () => { + if (isEditable) { + return ; + } + return {emptyLabel}; + }; + + const renderValue = (rawValue) => { + if (!rawValue) { + return renderEmptyLabel(); + } + let finalValue = rawValue; + + if (userSuppliedValue) { + finalValue += `: ${userSuppliedValue}`; + } + + return finalValue; + }; + + const renderConfirmationMessage = () => { + if (!confirmationMessageDefinition || !confirmationValue) { + return null; + } + return intl.formatMessage(confirmationMessageDefinition, { + value: confirmationValue, + }); + }; + + return ( + +
+ + + + {firstNameFieldAttributes.label} + + { handleChange(e, firstNameFieldAttributes.name); }} + {...others} + /> + + + + {lastNameFieldAttributes.label} + + { handleChange(e, lastNameFieldAttributes.name); }} + {...others} + /> + + {!!helpText && {helpText}} + {fieldError != null && {fieldError}} + {others.children} + +

+ { + // Swallow clicks if the state is pending. + // We do this instead of disabling the button to prevent + // it from losing focus (disabled elements cannot have focus). + // Disabling it would causes upstream issues in focus management. + // Swallowing the onSubmit event on the form would be better, but + // we would have to add that logic for every field given our + // current structure of the application. + if (saveState === 'pending') { e.preventDefault(); } + }} + disabledStates={[]} + /> + +

+
+ {['name', 'verified_name'].includes(name) && } + + ), + default: ( +
+
+
{label}
+ {isEditable ? ( + + ) : null} +
+

+ {renderValue(fullName)} +

+

{renderConfirmationMessage() || helpText}

+
+ ), + }} + /> + ); +}; + +NameField.propTypes = { + name: PropTypes.string.isRequired, + label: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.node]), + emptyLabel: PropTypes.node, + type: PropTypes.string.isRequired, + fullNameValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + firstNameValue: PropTypes.string, + lastNameValue: PropTypes.string, + pendingNameChange: PropTypes.string, + verifiedName: PropTypes.shape({ + verified_name: PropTypes.string, + status: PropTypes.string, + proctored_exam_attempt_id: PropTypes.number, + }), + userSuppliedValue: PropTypes.string, + saveState: PropTypes.oneOf(['default', 'pending', 'complete', 'error']), + error: PropTypes.string, + firstNameError: PropTypes.string, + lastNameError: PropTypes.string, + confirmationMessageDefinition: PropTypes.shape({ + id: PropTypes.string.isRequired, + defaultMessage: PropTypes.string.isRequired, + description: PropTypes.string, + }), + confirmationValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + helpText: PropTypes.node, + onEdit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onChange: PropTypes.func.isRequired, + isEditing: PropTypes.bool, + isEditable: PropTypes.bool, + isGrayedOut: PropTypes.bool, + intl: intlShape.isRequired, +}; + +NameField.defaultProps = { + fullNameValue: undefined, + firstNameValue: undefined, + lastNameValue: undefined, + pendingNameChange: null, + verifiedName: null, + saveState: undefined, + label: undefined, + emptyLabel: undefined, + error: null, + firstNameError: null, + lastNameError: null, + confirmationMessageDefinition: undefined, + confirmationValue: undefined, + helpText: undefined, + isEditing: false, + isEditable: true, + isGrayedOut: false, + userSuppliedValue: undefined, +}; + +export default connect(nameFieldSelector, { + onEdit: openForm, + onCancel: closeForm, +})(injectIntl(NameField)); diff --git a/src/account-settings/data/actions.js b/src/account-settings/data/actions.js index 27d8f7682..0f80510bf 100644 --- a/src/account-settings/data/actions.js +++ b/src/account-settings/data/actions.js @@ -105,9 +105,9 @@ export const savePreviousSiteLanguage = previousSiteLanguage => ({ payload: { previousSiteLanguage }, }); -export const saveMultipleSettings = (settingsArray, form = null) => ({ +export const saveMultipleSettings = (settingsArray, form = null, saveInSeparateCalls = true) => ({ type: SAVE_MULTIPLE_SETTINGS.BASE, - payload: { settingsArray, form }, + payload: { settingsArray, form, saveInSeparateCalls }, }); export const saveMultipleSettingsBegin = () => ({ diff --git a/src/account-settings/data/sagas.js b/src/account-settings/data/sagas.js index c27cbe9ef..9eb9c13e8 100644 --- a/src/account-settings/data/sagas.js +++ b/src/account-settings/data/sagas.js @@ -124,14 +124,24 @@ export function* handleSaveMultipleSettings(action) { try { yield put(saveMultipleSettingsBegin()); const { username, userId } = getAuthenticatedUser(); - const { settingsArray, form } = action.payload; - for (let i = 0; i < settingsArray.length; i += 1) { - const { formId, commitValues } = settingsArray[i]; + const { settingsArray, form, saveInSeparateCalls } = action.payload; + if (saveInSeparateCalls) { + for (let i = 0; i < settingsArray.length; i += 1) { + const { formId, commitValues } = settingsArray[i]; + yield put(saveSettingsBegin()); + const commitData = { [formId]: commitValues }; + const savedSettings = yield call(patchSettings, username, commitData, userId); + yield put(saveSettingsSuccess(savedSettings, commitData)); + } + } else { + const commitData = settingsArray.reduce((data, setting) => ( + { ...data, [setting.formId]: setting.commitValues } + ), {}); yield put(saveSettingsBegin()); - const commitData = { [formId]: commitValues }; const savedSettings = yield call(patchSettings, username, commitData, userId); yield put(saveSettingsSuccess(savedSettings, commitData)); } + yield put(saveMultipleSettingsSuccess(action)); if (form) { yield delay(1000); diff --git a/src/account-settings/data/selectors.js b/src/account-settings/data/selectors.js index 7650aa01e..d683bfa1a 100644 --- a/src/account-settings/data/selectors.js +++ b/src/account-settings/data/selectors.js @@ -128,6 +128,16 @@ export const editableFieldSelector = createStructuredSelector({ isEditing: isEditingSelector, }); +export const nameFieldSelector = createSelector( + editableFieldSelector, + accountSettingsSelector, + (editableFieldSettings, accountSettings) => ({ + ...editableFieldSettings, + firstNameError: accountSettings.errors?.first_name, + lastNameError: accountSettings.errors?.last_name, + }), +); + export const profileDataManagerSelector = createSelector( accountSettingsSelector, accountSettings => accountSettings.profileDataManager, diff --git a/src/account-settings/name-change/NameChange.jsx b/src/account-settings/name-change/NameChange.jsx index d08a840c5..10d56a9fe 100644 --- a/src/account-settings/name-change/NameChange.jsx +++ b/src/account-settings/name-change/NameChange.jsx @@ -62,7 +62,10 @@ const NameChangeModal = ({ })); } else { const draftProfileName = targetFormId === 'name' ? formValues.name : null; - dispatch(requestNameChange(username, draftProfileName, verifiedNameInput)); + const draftFirstName = targetFormId === 'name' ? formValues?.first_name : null; + const draftLastName = targetFormId === 'name' ? formValues?.last_name : null; + + dispatch(requestNameChange(username, draftProfileName, verifiedNameInput, draftFirstName, draftLastName)); } }; @@ -190,6 +193,8 @@ NameChangeModal.propTypes = { errors: PropTypes.shape({}).isRequired, formValues: PropTypes.shape({ name: PropTypes.string, + first_name: PropTypes.string, + last_name: PropTypes.string, verified_name: PropTypes.string, }).isRequired, saveState: PropTypes.string, diff --git a/src/account-settings/name-change/data/actions.js b/src/account-settings/name-change/data/actions.js index f80fbbbf5..efd0a0935 100644 --- a/src/account-settings/name-change/data/actions.js +++ b/src/account-settings/name-change/data/actions.js @@ -2,9 +2,11 @@ import { AsyncActionType } from '../../data/utils'; export const REQUEST_NAME_CHANGE = new AsyncActionType('ACCOUNT_SETTINGS', 'REQUEST_NAME_CHANGE'); -export const requestNameChange = (username, profileName, verifiedName) => ({ +export const requestNameChange = (username, profileName, verifiedName, firstName, lastName) => ({ type: REQUEST_NAME_CHANGE.BASE, - payload: { username, profileName, verifiedName }, + payload: { + username, profileName, verifiedName, firstName, lastName, + }, }); export const requestNameChangeBegin = () => ({ diff --git a/src/account-settings/name-change/data/sagas.js b/src/account-settings/name-change/data/sagas.js index dfbae8e87..4971a8807 100644 --- a/src/account-settings/name-change/data/sagas.js +++ b/src/account-settings/name-change/data/sagas.js @@ -17,7 +17,7 @@ export function* handleRequestNameChange(action) { try { yield put(requestNameChangeBegin()); if (action.payload.profileName) { - yield call(postNameChange, action.payload.profileName); + yield call(postNameChange, action.payload.profileName, action.payload.firstName, action.payload.lastName); profileName = action.payload.profileName; } yield call(postVerifiedName, { diff --git a/src/account-settings/name-change/data/service.js b/src/account-settings/name-change/data/service.js index 70a6cfc15..565850589 100644 --- a/src/account-settings/name-change/data/service.js +++ b/src/account-settings/name-change/data/service.js @@ -4,13 +4,19 @@ import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth'; import { handleRequestError } from '../../data/utils'; // eslint-disable-next-line import/prefer-default-export -export async function postNameChange(name) { +export async function postNameChange(name, firstName, lastName) { // Requests a pending name change, rather than saving the account name immediately const requestConfig = { headers: { Accept: 'application/json' } }; const requestUrl = `${getConfig().LMS_BASE_URL}/api/user/v1/accounts/name_change/`; + const nameChangePayload = { name }; + if (firstName && lastName) { + nameChangePayload.first_name = firstName; + nameChangePayload.last_name = lastName; + } + const { data } = await getAuthenticatedHttpClient() - .post(requestUrl, { name }, requestConfig) + .post(requestUrl, nameChangePayload, requestConfig) .catch(error => handleRequestError(error)); return data; diff --git a/src/account-settings/name-change/test/NameChange.test.jsx b/src/account-settings/name-change/test/NameChange.test.jsx index 1085f54ea..524111282 100644 --- a/src/account-settings/name-change/test/NameChange.test.jsx +++ b/src/account-settings/name-change/test/NameChange.test.jsx @@ -99,6 +99,8 @@ describe('NameChange', () => { const dispatchData = { payload: { profileName: null, + firstName: null, + lastName: null, username: 'edx', verifiedName: 'Verified Name', }, @@ -167,4 +169,41 @@ describe('NameChange', () => { render(reduxWrapper()); expect(window.location.pathname).toEqual('/id-verification'); }); + + it( + 'dispatches profileName with first and last name if first_name and last_name are available in settings', + async () => { + const dispatchData = { + payload: { + profileName: 'edx edx', + username: 'edx', + verifiedName: 'Verified Name', + firstName: 'first', + lastName: 'last', + }, + type: 'ACCOUNT_SETTINGS__REQUEST_NAME_CHANGE', + }; + const formProps = { + ...props, + targetFormId: 'name', + formValues: { + ...props.formValues, + first_name: 'first', + last_name: 'last', + }, + }; + + render(reduxWrapper()); + + const continueButton = screen.getByText('Continue'); + fireEvent.click(continueButton); + + const input = screen.getByPlaceholderText('Enter the name on your photo ID'); + fireEvent.change(input, { target: { value: 'Verified Name' } }); + + const submitButton = screen.getByText('Continue'); + fireEvent.click(submitButton); + expect(mockDispatch).toHaveBeenCalledWith(dispatchData); + }, + ); }); diff --git a/src/account-settings/test/AccountSettingsPage.test.jsx b/src/account-settings/test/AccountSettingsPage.test.jsx index 5acd4c563..bb5bbfe7f 100644 --- a/src/account-settings/test/AccountSettingsPage.test.jsx +++ b/src/account-settings/test/AccountSettingsPage.test.jsx @@ -11,6 +11,7 @@ import { IntlProvider, injectIntl } from '@edx/frontend-platform/i18n'; import AccountSettingsPage from '../AccountSettingsPage'; import mockData from './mockData'; +import { saveMultipleSettings, saveSettings } from '../data/actions'; const mockDispatch = jest.fn(); jest.mock('@edx/frontend-platform/analytics', () => ({ @@ -98,4 +99,104 @@ describe('AccountSettingsPage', () => { fireEvent.click(submitButton); }); + + it( + 'renders NameField for full name if first_name and last_name are available in account settings', + async () => { + const { getByText, rerender, getByLabelText } = render(reduxWrapper()); + + const fullNameText = getByText('Full name'); + const fullNameEditButton = fullNameText.parentElement.querySelector('button'); + + expect(fullNameEditButton).toBeInTheDocument(); + + store = mockStore({ + ...mockData, + accountSettings: { + ...mockData.accountSettings, + openFormId: 'name', + values: { + ...mockData.accountSettings.values, + first_name: 'John', + last_name: 'Doe', + }, + }, + }); + store.dispatch = jest.fn(store.dispatch); + + rerender(reduxWrapper()); + + const submitButton = screen.getByText('Save'); + expect(submitButton).toBeInTheDocument(); + + const firstNameField = getByLabelText('First name'); + const lastNameField = getByLabelText('Last name'); + + // Use fireEvent.change to simulate changing the selected value + fireEvent.change(firstNameField, { target: { value: 'John' } }); + fireEvent.change(lastNameField, { target: { value: 'Doe' } }); + + fireEvent.click(submitButton); + + expect(store.dispatch).toHaveBeenCalledWith(saveMultipleSettings( + [ + { + commitValues: 'John', + formId: 'first_name', + }, + { + commitValues: 'Doe', + formId: 'last_name', + }, + { + commitValues: 'John Doe', + formId: 'name', + }, + ], + 'name', + false, + )); + }, + ); + + it( + 'renders EditableField for full name if first_name and last_name are not available in account settings', + async () => { + const { getByText, rerender, getByLabelText } = render(reduxWrapper()); + + const fullNameText = getByText('Full name'); + const fullNameEditButton = fullNameText.parentElement.querySelector('button'); + + expect(fullNameEditButton).toBeInTheDocument(); + + store = mockStore({ + ...mockData, + accountSettings: { + ...mockData.accountSettings, + openFormId: 'name', + values: { + ...mockData.accountSettings.values, + }, + }, + }); + store.dispatch = jest.fn(store.dispatch); + + rerender(reduxWrapper()); + + const submitButton = screen.getByText('Save'); + expect(submitButton).toBeInTheDocument(); + + const fullName = getByLabelText('Full name'); + + // Use fireEvent.change to simulate changing the selected value + fireEvent.change(fullName, { target: { value: 'test_name' } }); + + fireEvent.click(submitButton); + + expect(store.dispatch).toHaveBeenCalledWith(saveSettings( + 'name', + 'test_name', + )); + }, + ); }); diff --git a/src/account-settings/test/NameField.test.jsx b/src/account-settings/test/NameField.test.jsx new file mode 100644 index 000000000..5905b4397 --- /dev/null +++ b/src/account-settings/test/NameField.test.jsx @@ -0,0 +1,207 @@ +import React from 'react'; +import { BrowserRouter as Router } from 'react-router-dom'; +import { Provider } from 'react-redux'; +import renderer from 'react-test-renderer'; +import configureStore from 'redux-mock-store'; + +import { IntlProvider, injectIntl } from '@edx/frontend-platform/i18n'; + +import { fireEvent, render, screen } from '@testing-library/react'; +import NameField from '../NameField'; + +jest.mock('@edx/frontend-platform/auth'); +jest.mock('../data/selectors', () => jest.fn().mockImplementation(() => ({ certPreferenceSelector: () => ({}) }))); + +const IntlNameField = injectIntl(NameField); + +const mockStore = configureStore(); + +describe('NameField', () => { + let props = {}; + let store = {}; + + const reduxWrapper = children => ( + + + {children} + + + ); + + beforeEach(() => { + store = mockStore(); + const onSubmit = jest.fn(); + const onChange = jest.fn(); + props = { + name: 'name', + label: 'Full name', + emptyLabel: 'Add name', + type: 'text', + fullNameValue: 'Test Name', + firstNameValue: '', + lastNameValue: '', + verifiedName: null, + userSuppliedValue: '', + pendingNameChange: '', + error: '', + firstNameError: '', + lastNameError: '', + saveState: 'default', + confirmationValue: 'Confirmation Value', + helpText: 'Helpful Text', + isEditing: false, + isEditable: true, + isGrayedOut: false, + onSubmit, + onChange, + }; + }); + + afterEach(() => jest.clearAllMocks()); + + it('renders NameField correctly with editing disabled', () => { + const tree = renderer.create(reduxWrapper()).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('renders NameField correctly with editing enabled', () => { + props = { + ...props, + isEditing: true, + }; + + const tree = renderer.create(reduxWrapper()).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('renders NameField with an error on full name', () => { + const errorProps = { + ...props, + isEditing: true, + error: 'This value is invalid.', + }; + + const { getByText } = render(reduxWrapper()); + + const errorMessage = getByText('This value is invalid.'); + expect(errorMessage).toBeInTheDocument(); + }); + + it('renders NameField with an error on first name', () => { + const errorProps = { + ...props, + isEditing: true, + firstNameError: 'This value is invalid.', + }; + + const { getByText } = render(reduxWrapper()); + + const errorMessage = getByText('This value is invalid.'); + expect(errorMessage).toBeInTheDocument(); + }); + + it('renders NameField with an error on last name', () => { + const errorProps = { + ...props, + isEditing: true, + lastNameError: 'This value is invalid.', + }; + + const { getByText } = render(reduxWrapper()); + + const errorMessage = getByText('This value is invalid.'); + expect(errorMessage).toBeInTheDocument(); + }); + + it('display pendingName in NameField if available when verifiedName submit state is submitted', () => { + const componentProps = { + ...props, + pendingNameChange: 'Pending Name', + verifiedName: { + status: 'submitted', + }, + }; + + const { getByText } = render(reduxWrapper()); + + const pendingNameText = getByText('Pending Name'); + expect(pendingNameText).toBeInTheDocument(); + }); + + it('should not display pendingName when verifiedName submit state is not submitted', () => { + const componentProps = { + ...props, + pendingNameChange: 'Pending Name', + verifiedName: { + status: 'pending', + }, + }; + + const { queryByText } = render(reduxWrapper()); + + expect(queryByText('Pending Name')).not.toBeInTheDocument(); + }); + + it('display concatenated first and last name in full name if first or last name value is available', () => { + const componentProps = { + ...props, + firstNameValue: 'John', + lastNameValue: 'Doe', + }; + + const { getByText } = render(reduxWrapper()); + + const pendingNameText = getByText('John Doe'); + expect(pendingNameText).toBeInTheDocument(); + }); + + it('display full name in NameField if first and last name value are not available', () => { + const componentProps = { + ...props, + fullNameValue: 'John Doe', + firstNameValue: '', + lastNameValue: '', + }; + + const { getByText } = render(reduxWrapper()); + + const pendingNameText = getByText('John Doe'); + expect(pendingNameText).toBeInTheDocument(); + }); + + it('split full name in first and last name on editing if first and last name value not available ', () => { + const componentProps = { + ...props, + isEditing: true, + fullNameValue: '', + firstNameValue: 'John', + lastNameValue: 'Doe', + }; + + const { getByLabelText } = render(reduxWrapper()); + + const firstNameText = getByLabelText('First name'); + const lastNameText = getByLabelText('Last name'); + + expect(firstNameText.value).toEqual('John'); + expect(lastNameText.value).toEqual('Doe'); + }); + + it('submit full name, first name and last name on save ', () => { + const componentProps = { + ...props, + isEditing: true, + fullNameValue: '', + firstNameValue: 'John', + lastNameValue: 'Doe', + }; + + const { getByText } = render(reduxWrapper()); + + const submitButton = getByText('Save'); + expect(submitButton).toBeInTheDocument(); + + fireEvent.click(submitButton); + expect(props.onSubmit).toHaveBeenCalledWith('name', 'John Doe', 'John', 'Doe'); + }); +}); diff --git a/src/account-settings/test/__snapshots__/NameField.test.jsx.snap b/src/account-settings/test/__snapshots__/NameField.test.jsx.snap new file mode 100644 index 000000000..d3e4e8059 --- /dev/null +++ b/src/account-settings/test/__snapshots__/NameField.test.jsx.snap @@ -0,0 +1,189 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`NameField renders NameField correctly with editing disabled 1`] = ` +
+
+
+
+
+ Full name +
+ +
+

+ Test Name +

+

+ Helpful Text +

+
+
+
+`; + +exports[`NameField renders NameField correctly with editing enabled 1`] = ` +
+
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+ Helpful Text +
+
+
+
+ +
+
+
+

+ + +

+
+
+
+`;