Skip to content

Commit

Permalink
test: improve coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
bra-i-am committed Feb 26, 2025
1 parent 9301a87 commit 9762d3b
Show file tree
Hide file tree
Showing 3 changed files with 243 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/account-settings/AccountSettingsPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ class AccountSettingsPage extends React.Component {
/>
{this.props.extendedProfileFields
.sort(moveCheckboxFieldsToEnd).map((fieldDescription) => {
const fieldValue = this.props.formValues.extended_profile.find(
const fieldValue = this.props.formValues.extended_profile?.find(
(field) => field.field_name === fieldDescription.name,

Check warning on line 705 in src/account-settings/AccountSettingsPage.jsx

View check run for this annotation

Codecov / codecov/patch

src/account-settings/AccountSettingsPage.jsx#L703-L705

Added lines #L703 - L705 were not covered by tests
);

Expand Down
211 changes: 211 additions & 0 deletions src/account-settings/data/sagas.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
import { runSaga } from 'redux-saga';
import { getAuthenticatedUser } from '@edx/frontend-platform/auth';
import {
fetchSettingsBegin,
fetchSettingsSuccess,
fetchSettingsFailure,
saveSettingsBegin,
saveSettingsSuccess,
fetchTimeZonesSuccess,
getExtendedProfileFieldsBegin,
getExtendedProfileFieldsSuccess,
getExtendedProfileFieldsFailure,
} from './actions';
import {
getSettings,
patchSettings,
getTimeZones,
getExtendedProfileFields,
} from './service';
import {
handleFetchSettings,
handleSaveSettings,
handleFetchTimeZones,
fetchThirdPartyAuthContext,
} from './sagas';

jest.mock('@edx/frontend-platform/auth', () => ({
getAuthenticatedUser: jest.fn(), // Mock de la función
}));

jest.mock('./service', () => ({
getSettings: jest.fn(),
patchSettings: jest.fn(),
getTimeZones: jest.fn(),
getVerifiedNameHistory: jest.fn(),
getExtendedProfileFields: jest.fn(), // Asegurar que está incluido aquí
}));

describe('Saga Tests', () => {
test('handleFetchSettings success', async () => {
const dispatched = [];
const mockUser = { username: 'testuser', userId: 1, roles: [] };
const mockSettings = {
values: {},
thirdPartyAuthProviders: {},
profileDataManager: {},
timeZones: {},
verifiedNameHistory: undefined,
};
getAuthenticatedUser.mockReturnValue(mockUser);
getSettings.mockResolvedValue(mockSettings);

await runSaga(
{
dispatch: (action) => dispatched.push(action),
},
handleFetchSettings,
).toPromise();

expect(dispatched).toContainEqual(fetchSettingsBegin());
expect(dispatched).toContainEqual(fetchSettingsSuccess({
// due to sagas.js and its ...values, we have to add the ...rest in values to pass test
...mockSettings,
values: {
values: mockSettings.values,
verifiedNameHistory: undefined,
},
}));
});

test('handleFetchSettings failure', async () => {
const dispatched = [];
const errorMessage = 'Failed to fetch';

getAuthenticatedUser.mockReturnValue({ username: 'testuser', userId: 1, roles: [] });
getSettings.mockRejectedValue(new Error(errorMessage));

await expect(runSaga(
{
dispatch: (action) => dispatched.push(action),
},
handleFetchSettings,
).toPromise()).rejects.toThrow(errorMessage);

expect(dispatched).toContainEqual(fetchSettingsBegin());
expect(dispatched).toContainEqual(fetchSettingsFailure(errorMessage));
});

test('handleSaveSettings success', async () => {
const dispatched = [];
const mockUser = { username: 'testuser', userId: 1 };
const mockAction = {
payload: {
commitValues: { exampleKey: 'exampleValue' },
formId: 'someForm',
extendedProfile: {}, // Asegura que no sea undefined
},
};
const mockSavedValues = {};

getAuthenticatedUser.mockReturnValue(mockUser);
patchSettings.mockResolvedValue(mockSavedValues);

await runSaga(
{
dispatch: (action) => dispatched.push(action),
},
handleSaveSettings,
mockAction,
).toPromise();

expect(dispatched).toContainEqual(saveSettingsBegin());
expect(dispatched).toContainEqual(saveSettingsSuccess(
mockSavedValues,
{ [mockAction.payload.formId]: mockAction.payload.commitValues },
));
});

test('handleFetchTimeZones success', async () => {
const dispatched = [];
const mockedAction = { payload: { country: 'US' } };
const mockResponse = ['EST', 'PST'];

getTimeZones.mockResolvedValue(mockResponse);

await runSaga(
{
dispatch: (action) => dispatched.push(action),
},
handleFetchTimeZones,
mockedAction,
).toPromise();

expect(dispatched).toContainEqual(fetchTimeZonesSuccess(mockResponse, 'US'));
});

test('fetchThirdPartyAuthContext success', async () => {
const dispatched = [];
const mockedAction = { payload: { urlParams: {} } };
const mockFields = { field1: 'value1' };

getExtendedProfileFields.mockResolvedValue({ fields: mockFields });

await runSaga(
{
dispatch: (action) => dispatched.push(action),
},
fetchThirdPartyAuthContext,
mockedAction,
).toPromise();

expect(dispatched).toContainEqual(getExtendedProfileFieldsBegin());
expect(dispatched).toContainEqual(getExtendedProfileFieldsSuccess(mockFields));
});

test('fetchThirdPartyAuthContext failure', async () => {
const dispatched = [];
const mockedAction = { payload: { urlParams: {} } };

getExtendedProfileFields.mockRejectedValue(new Error('API error'));

await expect(runSaga(
{
dispatch: (action) => dispatched.push(action),
},
fetchThirdPartyAuthContext,
mockedAction,
).toPromise()).rejects.toThrow('API error');

expect(dispatched).toContainEqual(getExtendedProfileFieldsBegin());
expect(dispatched).toContainEqual(getExtendedProfileFieldsFailure());
});

test('getExtendedProfileFields success', async () => {
const dispatched = [];
const mockUrlParams = { param1: 'value1' };
const mockFields = [{ name: 'field1', value: 'value1' }];

getExtendedProfileFields.mockResolvedValue({ fields: mockFields });

await runSaga(
{
dispatch: (action) => dispatched.push(action),
},
fetchThirdPartyAuthContext,
{ payload: { urlParams: mockUrlParams } },
).toPromise();

expect(dispatched).toContainEqual(getExtendedProfileFieldsBegin());
expect(dispatched).toContainEqual(getExtendedProfileFieldsSuccess(mockFields));
});

test('getExtendedProfileFields failure', async () => {
const dispatched = [];
const mockUrlParams = { param1: 'value1' };
const errorMessage = 'API error';

getExtendedProfileFields.mockRejectedValue(new Error(errorMessage));

await expect(runSaga(
{
dispatch: (action) => dispatched.push(action),
},
fetchThirdPartyAuthContext,
{ payload: { urlParams: mockUrlParams } },
).toPromise()).rejects.toThrow(errorMessage);

expect(dispatched).toContainEqual(getExtendedProfileFieldsBegin());
expect(dispatched).toContainEqual(getExtendedProfileFieldsFailure());
});
});
32 changes: 31 additions & 1 deletion src/tests/utils.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { compareVerifiedNamesByCreatedDate, getMostRecentApprovedOrPendingVerifiedName } from '../utils';
import { compareVerifiedNamesByCreatedDate, getMostRecentApprovedOrPendingVerifiedName, moveCheckboxFieldsToEnd } from '../utils';

describe('getMostRecentApprovedOrPendingVerifiedName', () => {
it('returns correct verified name if one exists', () => {
Expand Down Expand Up @@ -80,4 +80,34 @@ describe('compareVerifiedNamesByCreatedDate', () => {

expect(compareVerifiedNamesByCreatedDate(a, b)).toBeGreaterThan(0);
});

describe('moveCheckboxFieldsToEnd', () => {
it('returns 1 when first field is checkbox and second field is not', () => {
const a = { type: 'checkbox' };
const b = { type: 'text' };

expect(moveCheckboxFieldsToEnd(a, b)).toEqual(1);
});

it('returns -1 when first field is not checkbox and second field is', () => {
const a = { type: 'text' };
const b = { type: 'checkbox' };

expect(moveCheckboxFieldsToEnd(a, b)).toEqual(-1);
});

it('returns 0 when both fields are checkboxes', () => {
const a = { type: 'checkbox' };
const b = { type: 'checkbox' };

expect(moveCheckboxFieldsToEnd(a, b)).toEqual(0);
});

it('returns 0 when neither field is a checkbox', () => {
const a = { type: 'text' };
const b = { type: 'text' };

expect(moveCheckboxFieldsToEnd(a, b)).toEqual(0);
});
});
});

0 comments on commit 9762d3b

Please sign in to comment.