Skip to content

Commit

Permalink
chore: update additional tests
Browse files Browse the repository at this point in the history
  • Loading branch information
brobro10000 committed Feb 11, 2025
1 parent 9205534 commit 5a47226
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 37 deletions.
1 change: 0 additions & 1 deletion src/components/app/data/hooks/useBFF.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export default function useBFF({
const matchedBFFQuery = resolveBFFQuery(
location.pathname,
);
console.log(enterpriseSlug, 'slug');
// Determine which query to call, the original hook or the new BFF
let queryConfig = {};
if (matchedBFFQuery) {
Expand Down
106 changes: 81 additions & 25 deletions src/components/app/data/hooks/useEnterpriseCustomer.test.jsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,109 @@
import { renderHook } from '@testing-library/react-hooks';
import { QueryClientProvider } from '@tanstack/react-query';
import { AppContext } from '@edx/frontend-platform/react';
import { MemoryRouter, useParams } from 'react-router-dom';
import { authenticatedUserFactory, enterpriseCustomerFactory } from '../services/data/__factories__';
import useEnterpriseCustomer from './useEnterpriseCustomer';
import { queryClient } from '../../../../utils/tests';
import { fetchEnterpriseLearnerData } from '../services';
import { fetchEnterpriseLearnerDashboard, fetchEnterpriseLearnerData } from '../services';

jest.mock('../services', () => ({
...jest.requireActual('../services'),
fetchEnterpriseLearnerData: jest.fn().mockResolvedValue(null),
fetchEnterpriseLearnerDashboard: jest.fn().mockResolvedValue(null),
}));
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: jest.fn(),
}));
const mockEnterpriseCustomer = enterpriseCustomerFactory();
const mockAuthenticatedUser = authenticatedUserFactory();
const mockEnterpriseLearnerData = {
enterpriseCustomer: mockEnterpriseCustomer,
enterpriseCustomerUserRoleAssignments: [],
activeEnterpriseCustomer: null,
activeEnterpriseCustomerUserRoleAssignments: [],
transformed: {
enterpriseCustomer: mockEnterpriseCustomer,
enterpriseCustomerUserRoleAssignments: [],
activeEnterpriseCustomer: null,
activeEnterpriseCustomerUserRoleAssignments: [],
allLinkedEnterpriseCustomerUsers: [],
staffEnterpriseCustomer: null,
enterpriseFeatures: {
isBFFEnabled: false,
},
},
};
const mockBFFDashboardData = {
enterpriseCustomer: {
...mockEnterpriseCustomer,
isBFFEnabled: true,
},
allLinkedEnterpriseCustomerUsers: [],
enterpriseFeatures: {},
staffEnterpriseCustomer: null,
enterpriseFeatures: {
isBFFEnabled: true,
},
enterpriseCustomerUserSubsidies: {
subscriptions: {
customerAgreement: {},
subscriptionLicenses: [],
subscriptionLicensesByStatus: {
activated: [],
assigned: [],
expired: [],
revoked: [],
},
},
},
enterpriseCourseEnrollments: [],
errors: [],
warnings: [],
};

const mockExpectedEnterpriseCustomers = (isMatchedRoute) => (isMatchedRoute
? mockBFFDashboardData.enterpriseCustomer
: mockEnterpriseLearnerData.transformed.enterpriseCustomer);

describe('useEnterpriseCustomer', () => {
const Wrapper = ({ children }) => (
const Wrapper = ({ routes = null, children }) => (
<QueryClientProvider client={queryClient()}>
<AppContext.Provider value={{ authenticatedUser: mockAuthenticatedUser }}>
{children}
</AppContext.Provider>
<MemoryRouter initialEntries={[routes]}>
<AppContext.Provider value={{ authenticatedUser: mockAuthenticatedUser }}>
{children}
</AppContext.Provider>
</MemoryRouter>
</QueryClientProvider>
);
beforeEach(() => {
jest.clearAllMocks();
fetchEnterpriseLearnerData.mockResolvedValue(mockEnterpriseLearnerData);
fetchEnterpriseLearnerDashboard.mockResolvedValue(mockBFFDashboardData);
useParams.mockReturnValue({ enterpriseSlug: 'test-slug' });
});
it('should return enterprise customer metadata correctly', async () => {
const { result, waitForNextUpdate } = renderHook(() => useEnterpriseCustomer(), { wrapper: Wrapper });
it.each([
{ isMatchedRoute: false },
{ isMatchedRoute: true },
])('should return enterprise customers correctly (%s)', async ({ isMatchedRoute }) => {
const mockSelect = jest.fn(data => data.transformed);
const { result, waitForNextUpdate } = renderHook(
() => {
if (isMatchedRoute) {
return useEnterpriseCustomer({ select: mockSelect });
}
return useEnterpriseCustomer();
},
{
wrapper: ({ children }) => Wrapper({
routes: isMatchedRoute ? '/test-enterprise' : 'test-enterprise/search',
children,
}),
},
);
await waitForNextUpdate();
const actualEnterpriseCustomer = result.current.data;
expect(actualEnterpriseCustomer.uuid).toEqual(mockEnterpriseCustomer.uuid);
expect(actualEnterpriseCustomer.slug).toEqual(mockEnterpriseCustomer.slug);
});
it('should return enterprise customer metadata correctly with select', async () => {
const { result, waitForNextUpdate } = renderHook(() => useEnterpriseCustomer({
select: (data) => data,
}), { wrapper: Wrapper });
await waitForNextUpdate();
const actualEnterpriseCustomerSelectArgs = result.current.data;
expect(actualEnterpriseCustomerSelectArgs.original).toEqual(mockEnterpriseLearnerData);
expect(actualEnterpriseCustomerSelectArgs.transformed).toEqual(mockEnterpriseCustomer);
if (isMatchedRoute) {
expect(mockSelect).toHaveBeenCalledTimes(2);
} else {
expect(mockSelect).toHaveBeenCalledTimes(0);
}

const actualEnterpriseFeatures = result.current.data;
expect(actualEnterpriseFeatures).toEqual(mockExpectedEnterpriseCustomers(isMatchedRoute));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ describe('fetchEnterpriseLearnerData', () => {
enterpriseCustomer: expectedEnterpriseCustomer,
})),
staffEnterpriseCustomer: isStaffUser ? expectedEnterpriseCustomer : undefined,
shouldUpdateActiveEnterpriseCustomerUser: null,
});
});

Expand All @@ -192,6 +193,7 @@ describe('fetchEnterpriseLearnerData', () => {
activeEnterpriseCustomerUserRoleAssignments: [],
allLinkedEnterpriseCustomerUsers: [],
staffEnterpriseCustomer: null,
shouldUpdateActiveEnterpriseCustomerUser: null,
});
});
});
Expand Down
2 changes: 0 additions & 2 deletions src/components/app/routes/loaders/rootLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ const makeRootLoader: Types.MakeRouteLoaderFunctionWithQueryClient = function ma
);
}

console.log(enterpriseLearnerData);

let {
enterpriseCustomer,
activeEnterpriseCustomer,
Expand Down
47 changes: 38 additions & 9 deletions src/components/app/routes/loaders/tests/rootLoader.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,22 @@ import {
activateOrAutoApplySubscriptionLicense,
extractEnterpriseCustomer,
getBaseSubscriptionsData,
isBFFEnabled,
queryAcademiesList,
queryBrowseAndRequestConfiguration,
queryContentHighlightsConfiguration,
queryCouponCodeRequests,
queryCouponCodes,
queryEnterpriseLearner,
queryEnterpriseLearnerDashboardBFF,
queryEnterpriseLearnerOffers,
queryLicenseRequests,
queryNotices,
queryRedeemablePolicies,
querySubscriptions,
queryNotices,
updateUserActiveEnterprise,
} from '../../../data';
import { authenticatedUserFactory, enterpriseCustomerFactory } from '../../../data/services/data/__factories__';
import { isBFFEnabled } from '../../../data/utils';
import { LICENSE_STATUS } from '../../../../enterprise-user-subsidy/data/constants';

jest.mock('@edx/frontend-platform/config', () => ({
Expand Down Expand Up @@ -119,7 +120,9 @@ describe('rootLoader', () => {
});
});

it('ensures only the enterprise-learner query is called if there is no active enterprise customer user', async () => {
it.each([
{ isMatchedRoute: true }, { isMatchedRoute: false },
])('ensures only the enterprise-learner query is called if there is no active enterprise customer user, (%s)', async ({ isMatchedRoute }) => {
const enterpriseLearnerQuery = queryEnterpriseLearner(mockAuthenticatedUser.username, mockEnterpriseCustomer.slug);
when(mockQueryClient.ensureQueryData).calledWith(
expect.objectContaining({
Expand All @@ -129,13 +132,15 @@ describe('rootLoader', () => {
enterpriseCustomer: undefined,
activeEnterpriseCustomer: undefined,
});

const routeMetadata = isMatchedRoute
? { path: '/:enterpriseSlug', initialEntries: [`/${mockEnterpriseCustomer.slug}`] }
: { path: '/:enterpriseSlug/search', initialEntries: [`/${mockEnterpriseCustomer.slug}/search`] };
renderWithRouterProvider({
path: '/:enterpriseSlug',
path: routeMetadata.path,
element: <div>hello world</div>,
loader: makeRootLoader(mockQueryClient),
}, {
initialEntries: [`/${mockEnterpriseCustomer.slug}`],
initialEntries: routeMetadata.initialEntries,
});

expect(await screen.findByText('hello world')).toBeInTheDocument();
Expand All @@ -159,6 +164,7 @@ describe('rootLoader', () => {
isStaffUser: false,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF disabled, non-staff user is linked to requested customer, resolves
// requested customer, does not need to update active enterprise, needs
Expand All @@ -174,6 +180,7 @@ describe('rootLoader', () => {
isStaffUser: false,
shouldActivateSubscriptionLicense: true,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF disabled, non-staff user is linked to requested customer, resolves
// requested customer, needs update to active enterprise, does not
Expand All @@ -189,6 +196,7 @@ describe('rootLoader', () => {
isStaffUser: false,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF disabled, non-staff user is not linked to requested customer, resolves
// linked customer, does not need to update active enterprise, does not
Expand All @@ -203,6 +211,7 @@ describe('rootLoader', () => {
isStaffUser: false,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF disabled, staff user is not linked to requested customer, resolves
// requested customer, does not need to update active enterprise, does not
Expand All @@ -217,6 +226,7 @@ describe('rootLoader', () => {
isStaffUser: true,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF disabled, staff user is linked to requested customer, resolves
// requested customer, needs update to active enterprise, does not
Expand All @@ -232,6 +242,7 @@ describe('rootLoader', () => {
isStaffUser: true,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: false,
isMatchedRoute: false,
},
// BFF enabled, non-staff user is linked to requested customer, resolves
// requested customer, needs update to active enterprise, does not
Expand All @@ -247,6 +258,7 @@ describe('rootLoader', () => {
isStaffUser: false,
shouldActivateSubscriptionLicense: false,
hasResolvedBFFQuery: true,
isMatchedRoute: true,
},
])('ensures all requisite root loader queries are resolved with an active enterprise customer user (%s)', async ({
isStaffUser,
Expand All @@ -256,13 +268,14 @@ describe('rootLoader', () => {
allLinkedEnterpriseCustomerUsers,
shouldActivateSubscriptionLicense,
hasResolvedBFFQuery,
isMatchedRoute,
}) => {
// Mock whether BFF enabled for enterprise customer and/or user
isBFFEnabled.mockReturnValue(hasResolvedBFFQuery);

const enterpriseLearnerQuery = queryEnterpriseLearner(mockAuthenticatedUser.username, enterpriseSlug);
const enterpriseLearnerQueryTwo = queryEnterpriseLearner(mockAuthenticatedUser.username, enterpriseCustomer.slug);

const enterpriseBFFQuery = queryEnterpriseLearnerDashboardBFF(enterpriseSlug);
// Mock the enterprise-learner query to return an active enterprise customer user.
when(mockQueryClient.ensureQueryData).calledWith(
expect.objectContaining({
Expand All @@ -285,6 +298,18 @@ describe('rootLoader', () => {
staffEnterpriseCustomer: isStaffUser ? enterpriseCustomer : undefined,
});

// Mock the BFF query to return the enterprise customer user metadata
when(mockQueryClient.ensureQueryData).calledWith(
expect.objectContaining({
queryKey: enterpriseBFFQuery.queryKey,
}),
).mockResolvedValue({
enterpriseCustomer,
allLinkedEnterpriseCustomerUsers,
staffEnterpriseCustomer: isStaffUser ? enterpriseCustomer : undefined,
shouldUpdateActiveEnterpriseCustomerUser: false,
});

// Mock redeemable policies query
const mockRedeemablePolicies = {
redeemablePolicies: [],
Expand Down Expand Up @@ -334,12 +359,16 @@ describe('rootLoader', () => {
}),
).mockResolvedValue(mockSubscriptionsData);

const routeMetadata = isMatchedRoute
? { path: '/:enterpriseSlug', initialEntries: [`/${enterpriseSlug}`] }
: { path: '/:enterpriseSlug/search', initialEntries: [`/${enterpriseSlug}/search`] };

renderWithRouterProvider({
path: '/:enterpriseSlug',
path: routeMetadata.path,
element: <div data-testid="dashboard" />,
loader: makeRootLoader(mockQueryClient),
}, {
initialEntries: [`/${enterpriseSlug}`],
initialEntries: routeMetadata.initialEntries,
});

const isLinked = allLinkedEnterpriseCustomerUsers.some((ecu) => ecu.enterpriseCustomer.slug === enterpriseSlug);
Expand Down

0 comments on commit 5a47226

Please sign in to comment.