diff --git a/packages/client/package.json b/packages/client/package.json index 3af3d7ae0ef..707a73e0921 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -16,7 +16,7 @@ "open:cov": "yarn test && opener coverage/index.html", "lint": "yarn lint:css && yarn lint:ts", "lint:css": "stylelint 'src/**/*.{ts,tsx}'", - "lint:ts": "eslint --fix './src/**/*.{ts,tsx}' --max-warnings=349", + "lint:ts": "eslint --fix './src/**/*.{ts,tsx}' --max-warnings=1000", "test:compilation": "tsc --noEmit", "extract:translations": "bash extract-translations.sh", "generate-gateway-types": "NODE_OPTIONS=--dns-result-order=ipv4first graphql-codegen --config codegen.ts && prettier --write src/utils/gateway.ts", diff --git a/packages/client/src/App.test.tsx b/packages/client/src/App.test.tsx index affae8a93b9..89457d56a55 100644 --- a/packages/client/src/App.test.tsx +++ b/packages/client/src/App.test.tsx @@ -59,10 +59,11 @@ describe('when user has a valid token in url but an expired one in localStorage' beforeEach(async () => { getItem.mockReturnValue(expiredToken) window.history.replaceState('', '', '?token=' + validToken) - await createTestApp() }) it("doesn't redirect user to SSO", async () => { + await createTestApp() + expect(assign.mock.calls).toHaveLength(0) }) @@ -72,7 +73,12 @@ describe('when user has a valid token in url but an expired one in localStorage' window.history.replaceState({}, '', '?token=' + token) - await createTestApp() + const { app } = await createTestApp( + { waitUntilOfflineCountryConfigLoaded: false }, + ['/?token=' + token] + ) + + app.debug() expect(assign.mock.calls).toHaveLength(0) }) }) @@ -130,36 +136,36 @@ describe('when user has a valid token in local storage', () => { describe('it handles react errors', () => { it('displays react error page', async () => { - const { store, history } = createStore() + const { store } = createStore() function Problem(): JSX.Element { throw new Error('Error thrown.') } - const testComponent = await createTestComponent( + const { component } = await createTestComponent( , - { store, history } + { store } ) - expect(testComponent.find('#GoToHomepage').hostNodes()).toHaveLength(1) + expect(component.find('#GoToHomepage').hostNodes()).toHaveLength(1) }) }) describe('it handles react unauthorized errors', () => { it('displays react error page', async () => { - const { store, history } = createStore() + const { store } = createStore() function Problem(): JSX.Element { throw new Error('401') } - const testComponent = await createTestComponent( + const { component } = await createTestComponent( , - { store, history } + { store } ) - expect(testComponent.find('#GoToHomepage').hostNodes()).toHaveLength(1) + expect(component.find('#GoToHomepage').hostNodes()).toHaveLength(1) - testComponent.find('#GoToHomepage').hostNodes().simulate('click') + component.find('#GoToHomepage').hostNodes().simulate('click') }) }) diff --git a/packages/client/src/App.tsx b/packages/client/src/App.tsx index 480cfed1e92..7acf05f0be0 100644 --- a/packages/client/src/App.tsx +++ b/packages/client/src/App.tsx @@ -8,6 +8,18 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ +import { ErrorBoundary } from '@client/components/ErrorBoundary' +import { StyledErrorBoundary } from '@client/components/StyledErrorBoundary' +import { I18nContainer } from '@client/i18n/components/I18nContainer' +import { useApolloClient } from '@client/utils/apolloClient' +import { ApolloProvider } from '@client/utils/ApolloProvider' +import { getTheme } from '@opencrvs/components/lib/theme' +import { Provider } from 'react-redux' +import { RouterProvider, createBrowserRouter, Outlet } from 'react-router-dom' +import styled, { createGlobalStyle, ThemeProvider } from 'styled-components' + +import * as React from 'react' + import { NotificationComponent } from '@client/components/Notification' import { Page } from '@client/components/Page' import { ProtectedPage } from '@client/components/ProtectedPage' @@ -15,7 +27,6 @@ import { ProtectedRoute } from '@client/components/ProtectedRoute' import ScrollToTop from '@client/components/ScrollToTop' import { SessionExpireConfirmation } from '@client/components/SessionExpireConfirmation' import * as routes from '@client/navigation/routes' -import styled from 'styled-components' import { OfficeHome } from '@client/views/OfficeHome/OfficeHome' import { FieldAgentList } from '@client/views/Performance/FieldAgentList' import { CollectorForm } from '@client/views/PrintCertificate/collectorForm/CollectorForm' @@ -26,417 +37,368 @@ import { ReviewForm } from '@client/views/RegisterForm/ReviewForm' import { SearchResult } from '@client/views/SearchResult/SearchResult' import { SelectVitalEvent } from '@client/views/SelectVitalEvent/SelectVitalEvent' import { SettingsPage } from '@client/views/Settings/SettingsPage' -import { PerformanceHome } from '@client/views/SysAdmin/Performance/PerformanceHome' import { CompletenessRates } from '@client/views/SysAdmin/Performance/CompletenessRates' +import { PerformanceHome } from '@client/views/SysAdmin/Performance/PerformanceHome' import { WorkflowStatus } from '@client/views/SysAdmin/Performance/WorkflowStatus' import { TeamSearch } from '@client/views/SysAdmin/Team/TeamSearch' import { CreateNewUser } from '@client/views/SysAdmin/Team/user/userCreation/CreateNewUser' -import * as React from 'react' -import { createBrowserRouter, Route, Routes } from 'react-router-dom' -import { CorrectionForm, CorrectionReviewForm } from './views/CorrectionForm' -import { VerifyCorrector } from './views/CorrectionForm/VerifyCorrector' -import { RecordAudit } from './views/RecordAudit/RecordAudit' -import { UserList } from './views/SysAdmin/Team/user/UserList' -import { SystemList } from './views/SysAdmin/Config/Systems/Systems' -import VSExport from './views/SysAdmin/Vsexports/VSExport' -import { AdvancedSearchConfig } from './views/SearchResult/AdvancedSearch' -import { ViewRecord } from '@client/views/ViewRecord/ViewRecord' -import { UserAudit } from './views/UserAudit/UserAudit' -import { AdvancedSearchResult } from '@client/views/AdvancedSearch/AdvancedSearchResult' -import { RegistrationList } from '@client/views/Performance/RegistrationsList' -import { PerformanceStatistics } from '@client/views/Performance/Statistics' -import { Leaderboards } from '@client/views/Performance/Leaderboards' -import { PerformanceDashboard } from '@client/views/Performance/Dashboard' import { SystemRoleType } from '@client/utils/gateway' -import { AdministrativeLevels } from '@client/views/Organisation/AdministrativeLevels' -import { VerifyCertificatePage } from '@client/views/VerifyCertificate/VerifyCertificatePage' +import { AdvancedSearchResult } from '@client/views/AdvancedSearch/AdvancedSearchResult' import { IssueCertificate } from '@client/views/IssueCertificate/IssueCertificate' import { IssuePayment } from '@client/views/IssueCertificate/IssueCollectorForm/IssuePayment' import { Home } from '@client/views/OfficeHome/Home' +import { AdministrativeLevels } from '@client/views/Organisation/AdministrativeLevels' +import { PerformanceDashboard } from '@client/views/Performance/Dashboard' +import { Leaderboards } from '@client/views/Performance/Leaderboards' +import { RegistrationList } from '@client/views/Performance/RegistrationsList' +import { PerformanceStatistics } from '@client/views/Performance/Statistics' +import { VerifyCertificatePage } from '@client/views/VerifyCertificate/VerifyCertificatePage' +import { ViewRecord } from '@client/views/ViewRecord/ViewRecord' + +import { ApolloClient, NormalizedCacheObject } from '@apollo/client' +import { AppStore } from './store' +import { Workqueues } from './v2-events/features/workqueues' +import { V2_ROOT_ROUTE } from './v2-events/routes/routes' +import { CorrectionForm, CorrectionReviewForm } from './views/CorrectionForm' +import { VerifyCorrector } from './views/CorrectionForm/VerifyCorrector' +import { ReloadModal } from './views/Modals/ReloadModal' +import { ReviewCertificate } from './views/PrintCertificate/ReviewCertificateAction' import { PrintRecord } from './views/PrintRecord/PrintRecord' +import { RecordAudit } from './views/RecordAudit/RecordAudit' import { ReviewCorrection } from './views/ReviewCorrection/ReviewCorrection' -import { ReviewCertificate } from './views/PrintCertificate/ReviewCertificateAction' +import { AdvancedSearchConfig } from './views/SearchResult/AdvancedSearch' import AllUserEmail from './views/SysAdmin/Communications/AllUserEmail/AllUserEmail' -import { ReloadModal } from './views/Modals/ReloadModal' -import { V2_ROOT_ROUTE } from './v2-events/routes/routes' -import { Workqueues } from './v2-events/features/workqueues' +import { SystemList } from './views/SysAdmin/Config/Systems/Systems' +import { UserList } from './views/SysAdmin/Team/user/UserList' +import VSExport from './views/SysAdmin/Vsexports/VSExport' +import { UserAudit } from './views/UserAudit/UserAudit' + +// Injecting global styles for the body tag - used only once +// eslint-disable-line +const GlobalStyle = createGlobalStyle` + body { + margin: 0; + padding: 0; + overflow-y: scroll; + } +` const MainSection = styled.section` flex-grow: 8; background: ${({ theme }) => theme.colors.background}; ` -/** - * The main application component that contains the routing logic for the application. - * In long run, router will be responsible for handling the routing logic for the entire application. - * When a new page is added, it should be added to the router rather than the App component. - */ -export const router = createBrowserRouter([ +export const routesConfig = [ { - path: '*', - Component: App + path: '/', + element: ( + + + + + + + + + + + + + + ), + children: [ + { path: routes.HOME, element: }, + { path: routes.SELECT_VITAL_EVENT, element: }, + { path: routes.SELECT_DEATH_INFORMANT, element: }, + { path: routes.SELECT_MARRIAGE_INFORMANT, element: }, + { path: routes.DRAFT_BIRTH_PARENT_FORM, element: }, + { + path: routes.VIEW_VERIFY_CERTIFICATE, + element: + }, + { + path: routes.DRAFT_BIRTH_PARENT_FORM_PAGE, + element: + }, + { + path: routes.DRAFT_BIRTH_PARENT_FORM_PAGE_GROUP, + element: + }, + { path: routes.DRAFT_DEATH_FORM, element: }, + { path: routes.DRAFT_DEATH_FORM_PAGE, element: }, + { path: routes.DRAFT_MARRIAGE_FORM, element: }, + { + path: routes.DRAFT_DEATH_FORM_PAGE_GROUP, + element: + }, + { path: routes.DRAFT_MARRIAGE_FORM_PAGE, element: }, + { + path: routes.DRAFT_MARRIAGE_FORM_PAGE_GROUP, + element: + }, + { path: routes.REVIEW_EVENT_PARENT_FORM_PAGE, element: }, + { + path: routes.REVIEW_EVENT_PARENT_FORM_PAGE_GROUP, + element: + }, + { path: routes.REVIEW_CORRECTION, element: }, + { path: routes.REGISTRAR_HOME, element: }, + { path: routes.REGISTRAR_HOME_TAB, element: }, + { path: routes.REGISTRAR_HOME_TAB_PAGE, element: }, + { + path: routes.ALL_USER_EMAIL, + element: ( + + + + ) + }, + { + path: routes.ADVANCED_SEARCH, + element: ( + + + + ) + }, + { + path: routes.ADVANCED_SEARCH_RESULT, + element: ( + + + + ) + }, + { path: routes.DECLARATION_RECORD_AUDIT, element: }, + { path: routes.SEARCH, element: }, + { path: routes.SEARCH_RESULT, element: }, + { path: routes.CERTIFICATE_COLLECTOR, element: }, + { path: routes.VERIFY_COLLECTOR, element: }, + { path: routes.VERIFY_CORRECTOR, element: }, + { path: routes.REVIEW_CERTIFICATE, element: }, + { path: routes.PRINT_CERTIFICATE_PAYMENT, element: }, + { path: routes.CERTIFICATE_CORRECTION, element: }, + { + path: routes.CERTIFICATE_CORRECTION_REVIEW, + element: + }, + { path: routes.SETTINGS, element: }, + { + path: routes.TEAM_USER_LIST, + element: ( + + + + ) + }, + { + path: routes.SYSTEM_LIST, + element: ( + + + + ) + }, + { + path: routes.VS_EXPORTS, + element: ( + + + + ) + }, + { path: routes.USER_PROFILE, element: }, + { path: routes.VIEW_RECORD, element: }, + { + path: routes.PERFORMANCE_REGISTRATIONS_LIST, + element: + }, + { + path: routes.PERFORMANCE_STATISTICS, + element: ( + + + + ) + }, + { + path: routes.PERFORMANCE_LEADER_BOARDS, + element: ( + + + + ) + }, + { + path: routes.PERFORMANCE_DASHBOARD, + element: ( + + + + ) + }, + { + path: routes.ORGANISATIONS_INDEX, + element: ( + + + + ) + }, + { path: routes.ISSUE_COLLECTOR, element: }, + { path: routes.ISSUE_VERIFY_COLLECTOR, element: }, + { path: routes.ISSUE_CERTIFICATE_PAYMENT, element: }, + { path: routes.PRINT_RECORD, element: }, + { + path: routes.PERFORMANCE_FIELD_AGENT_LIST, + element: + }, + { + path: routes.PERFORMANCE_HOME, + element: ( + + + + ) + }, + { + path: routes.EVENT_COMPLETENESS_RATES, + element: + }, + { + path: routes.WORKFLOW_STATUS, + element: + }, + { + path: routes.TEAM_SEARCH, + element: ( + + + + ) + }, + { + path: routes.CREATE_USER, + element: + }, + { + path: routes.CREATE_USER_ON_LOCATION, + element: + }, + { + path: routes.CREATE_USER_SECTION, + element: + }, + { + path: routes.REVIEW_USER_FORM, + element: + }, + { + path: routes.REVIEW_USER_DETAILS, + element: + }, + { path: V2_ROOT_ROUTE, element: } + ] } -]) +] +interface IAppProps { + client?: ApolloClient + store: AppStore + router: ReturnType +} +export function App({ client, store, router }: IAppProps) { + const { client: apolloClient } = useApolloClient(store) -export function App() { return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } - /> - - - - } - /> - - - - - } - /> - - - - - - - - - - - - - - - - } - /> - - - - - } - /> - - - - } - /> - - - - - - - - - - } - /> - - - - } - /> - - - - - } - /> - - - - } - /> - - - - - } - /> - - - - - - - - - - - } - /> - - - - - - - - - - - - + + + + + + + + + + + + + + ) } diff --git a/packages/client/src/components/DateRangePicker.test.tsx b/packages/client/src/components/DateRangePicker.test.tsx index 639a84ae8ed..63a8cb9bf3a 100644 --- a/packages/client/src/components/DateRangePicker.test.tsx +++ b/packages/client/src/components/DateRangePicker.test.tsx @@ -18,30 +18,31 @@ import { import { AppStore } from '@client/store' import { DateRangePicker } from '@client/components/DateRangePicker' import { waitForElement } from '@client/tests/wait-for-element' -import { History } from 'history' import { Mock, vi } from 'vitest' import startOfMonth from 'date-fns/startOfMonth' describe('date picker tests', () => { - let component: ReactWrapper + let component: ReactWrapper<{}, {}> let store: AppStore - let history: History + let onDatesChangeMock: Mock beforeEach(async () => { Date.now = vi.fn(() => 1592233232409) const appStore = await createTestStore() store = appStore.store - history = appStore.history + onDatesChangeMock = vi.fn() - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) + + component = testComponent }) describe('on desktop', () => { diff --git a/packages/client/src/components/GenericErrorToast.test.tsx b/packages/client/src/components/GenericErrorToast.test.tsx index e7049b80e72..c702862fb63 100644 --- a/packages/client/src/components/GenericErrorToast.test.tsx +++ b/packages/client/src/components/GenericErrorToast.test.tsx @@ -14,12 +14,11 @@ import * as React from 'react' import { GenericErrorToast } from './GenericErrorToast' describe('Test toast notification', () => { - const { store, history } = createStore() + const { store } = createStore() it('checks if the appropriate toast is rendered', async () => { - const component = await createTestComponent(, { - store, - history + const { component } = await createTestComponent(, { + store }) expect(component.find('#error-toast').hostNodes()).toHaveLength(1) diff --git a/packages/client/src/components/Header/Header.tsx b/packages/client/src/components/Header/Header.tsx index d33d381e3af..895818a0863 100644 --- a/packages/client/src/components/Header/Header.tsx +++ b/packages/client/src/components/Header/Header.tsx @@ -45,9 +45,12 @@ import { getRegisterForm } from '@client/forms/register/declaration-selectors' import { getOfflineData } from '@client/offline/selectors' import { IOfflineData } from '@client/offline/reducer' import { SearchCriteria } from '@client/utils/referenceApi' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' -import { stringify } from 'query-string' +import { parse, stringify } from 'query-string' type IStateProps = { userDetails: UserDetails | null @@ -137,9 +140,8 @@ const HeaderComponent = (props: IFullProps) => { } = props const getMobileHeaderActionProps = (activeMenuItem: ACTIVE_MENU_ITEM) => { - const locationId = new URLSearchParams(router.location.search).get( - 'locationId' - ) + const locationId = parse(router.location.search).locationId as string + if (activeMenuItem === ACTIVE_MENU_ITEM.PERFORMANCE) { return { mobileLeft: [ diff --git a/packages/client/src/components/LocationPicker.test.tsx b/packages/client/src/components/LocationPicker.test.tsx index 31534076eb7..802a75682bd 100644 --- a/packages/client/src/components/LocationPicker.test.tsx +++ b/packages/client/src/components/LocationPicker.test.tsx @@ -8,36 +8,34 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import React from 'react' -import { ReactWrapper } from 'enzyme' -import { createTestComponent, flushPromises } from '@client/tests/util' -import { LocationPicker } from './LocationPicker' import { AppStore, createStore } from '@client/store' +import { createTestComponent, flushPromises } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' -import { History } from 'history' +import { ReactWrapper } from 'enzyme' +import React from 'react' import { vi } from 'vitest' +import { LocationPicker } from './LocationPicker' describe('location picker tests', () => { let store: AppStore - let history: History let component: ReactWrapper const onChangeLocationMock = vi.fn() beforeAll(async () => { const appStore = createStore() store = appStore.store - history = appStore.history }) beforeEach(async () => { - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history }, + { store }, { attachTo: document.body } ) + component = testComponent }) afterEach(() => { diff --git a/packages/client/src/components/Notification.tsx b/packages/client/src/components/Notification.tsx index 1e57cf3bfeb..ffed4e42818 100644 --- a/packages/client/src/components/Notification.tsx +++ b/packages/client/src/components/Notification.tsx @@ -36,7 +36,7 @@ import { import { TOAST_MESSAGES } from '@client/user/userReducer' import * as routes from '@client/navigation/routes' import { withOnlineStatus } from '@client/views/OfficeHome/LoadingIndicator' -import { RouteComponentProps, withRouter } from './withRouter' +import { RouteComponentProps, withRouter } from './WithRouterProps' import { formatUrl } from '@client/navigation' type NotificationProps = ReturnType & { diff --git a/packages/client/src/components/Page.tsx b/packages/client/src/components/Page.tsx index 7452343e81e..6cdee91cf76 100644 --- a/packages/client/src/components/Page.tsx +++ b/packages/client/src/components/Page.tsx @@ -31,7 +31,7 @@ import { isRegisterFormReady } from '@client/forms/register/declaration-selector import { IOfflineData } from '@client/offline/reducer' import { isNavigatorOnline } from '@client/utils' import { LoadingBar } from '@opencrvs/components/src/LoadingBar/LoadingBar' -import { RouteComponentProps, withRouter } from './withRouter' +import { RouteComponentProps, withRouter } from './WithRouterProps' const StyledPage = styled.div` background: ${({ theme }) => theme.colors.background}; diff --git a/packages/client/src/components/ProfileMenu.test.tsx b/packages/client/src/components/ProfileMenu.test.tsx index f99af6da039..7945fe2db1f 100644 --- a/packages/client/src/components/ProfileMenu.test.tsx +++ b/packages/client/src/components/ProfileMenu.test.tsx @@ -19,11 +19,14 @@ import { getStorageUserDetailsSuccess } from '@opencrvs/client/src/profile/profi describe('when user opens profile menu without user details', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() - component = await createTestComponent(, { - store, - history - }) + const { store } = createStore() + const { component: testComponent } = await createTestComponent( + , + { + store + } + ) + component = testComponent }) it('open menu', () => { @@ -38,7 +41,7 @@ describe('when user opens profile menu without user details', () => { describe('when user opens profile menu with user details', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const details = userDetails details.name = [ { @@ -48,10 +51,13 @@ describe('when user opens profile menu with user details', () => { } ] store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(details))) - component = await createTestComponent(, { - store, - history - }) + const { component: testComponent } = await createTestComponent( + , + { + store + } + ) + component = testComponent }) it('open menu', () => { diff --git a/packages/client/src/components/ProtectedPage.tsx b/packages/client/src/components/ProtectedPage.tsx index fd99a1e1bee..8dcc6da1935 100644 --- a/packages/client/src/components/ProtectedPage.tsx +++ b/packages/client/src/components/ProtectedPage.tsx @@ -30,7 +30,7 @@ import { showPINUpdateSuccessToast } from '@client/notification/actions' import { CreatePin } from '@client/views/PIN/CreatePin' import { redirectToAuthentication } from '@client/profile/profileActions' import { LoadingBar } from '@opencrvs/components/src/LoadingBar/LoadingBar' -import { RouteComponentProps, withRouter } from './withRouter' +import { RouteComponentProps, withRouter } from './WithRouterProps' import { getAuthenticated } from '@client/profile/profileSelectors' import { IStoreState } from '@client/store' export const SCREEN_LOCK = 'screenLock' diff --git a/packages/client/src/components/ScrollToTop.tsx b/packages/client/src/components/ScrollToTop.tsx index 801a3a9a6df..8c5ed72437f 100644 --- a/packages/client/src/components/ScrollToTop.tsx +++ b/packages/client/src/components/ScrollToTop.tsx @@ -9,7 +9,7 @@ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ import React, { useEffect, ReactNode } from 'react' -import { RouteComponentProps, withRouter } from './withRouter' +import { RouteComponentProps, withRouter } from './WithRouterProps' type ScrollToTopProps = RouteComponentProps<{ children?: ReactNode }> diff --git a/packages/client/src/components/WithRouter.tsx b/packages/client/src/components/WithRouterProps.tsx similarity index 71% rename from packages/client/src/components/WithRouter.tsx rename to packages/client/src/components/WithRouterProps.tsx index 57cefb354c8..2a9745a1c81 100644 --- a/packages/client/src/components/WithRouter.tsx +++ b/packages/client/src/components/WithRouterProps.tsx @@ -1,3 +1,14 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * OpenCRVS is also distributed under the terms of the Civil Registration + * & Healthcare Disclaimer located at http://opencrvs.org/license. + * + * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. + */ + import { useLocation, useNavigate, diff --git a/packages/client/src/components/form/FormFieldGenerator.test.tsx b/packages/client/src/components/form/FormFieldGenerator.test.tsx index b15f46ad29e..9593b94721c 100644 --- a/packages/client/src/components/form/FormFieldGenerator.test.tsx +++ b/packages/client/src/components/form/FormFieldGenerator.test.tsx @@ -41,11 +41,11 @@ describe('form component', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const draft = createDeclaration(EventType.Birth) store.dispatch(storeDeclaration(draft)) const modifyDraft = vi.fn() - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { ]} />, { - store, - history + store } ) + + component = testComponent }) describe('when user is in the moth​​er section', () => { it('renders the page', async () => { @@ -150,8 +151,8 @@ describe('when field definition has location search input', () => { const modifyDraft = vi.fn() beforeEach(async () => { - const { store, history } = createStore() - component = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( { } ]} />, - { store, history } + { store } ) + + component = testComponent }) it('renders location search input without crashing', async () => { @@ -215,11 +218,11 @@ describe('when field definition has location search input', () => { describe('when user is in the register section', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const draft = createDeclaration(EventType.Birth) store.dispatch(storeDeclaration(draft)) const modifyDraft = vi.fn() - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { ]} />, { - store, - history + store } ) + + component = testComponent }) it('renders registration phone type as tel', () => { expect( @@ -257,11 +261,11 @@ describe('when field definition has nested fields', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const draft = createDeclaration(EventType.Birth) store.dispatch(storeDeclaration(draft)) const modifyDraft = vi.fn() - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { ]} />, { - store, - history + store } ) + + component = testComponent }) it('renders radio group with nested fields', () => { @@ -436,8 +441,8 @@ describe('when field definition has date field', () => { describe('in case of static date field', () => { beforeEach(async () => { - const { store, history } = createStore() - component = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( { } ]} />, - { store, history } + { store } ) + + component = testComponent }) it('shows validation errors for invalid date', async () => { @@ -473,8 +480,8 @@ describe('when field definition has number field', () => { const modifyDraftMock = vi.fn() beforeEach(async () => { - const { store, history } = createStore() - component = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( { ]} />, { - store, - history + store } ) + + component = testComponent }) it('field does not take input of non numeric characters', async () => { @@ -524,8 +532,8 @@ describe('when field definition has select field on mobile device', () => { beforeEach(async () => { window.HTMLElement.prototype.scrollIntoView = scrollMock - const { store, history } = createStore() - component = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( { ]} />, { - store, - history + store }, { attachTo: document.body } ) + + component = testComponent }) it('triggers scroll up when focus so that soft keyboard does not block options', async () => { diff --git a/packages/client/src/components/interface/DownloadButton.test.tsx b/packages/client/src/components/interface/DownloadButton.test.tsx index 61f39cf5529..deeea7b7e2a 100644 --- a/packages/client/src/components/interface/DownloadButton.test.tsx +++ b/packages/client/src/components/interface/DownloadButton.test.tsx @@ -11,7 +11,6 @@ import { createTestComponent, createTestStore } from '@client/tests/util' import { DownloadButton } from './DownloadButton' import { AppStore } from '@client/store' -import { History } from 'history' import * as React from 'react' import { DownloadAction } from '@client/forms' import { ReactWrapper } from 'enzyme' @@ -23,7 +22,7 @@ const { DOWNLOAD_STATUS } = declarationReducer describe('download button tests', () => { let store: AppStore - let history: History + let testComponent: ReactWrapper<{}, {}> let client: ApolloClient<{}> @@ -32,9 +31,9 @@ describe('download button tests', () => { beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history + client = createClient(store) - testComponent = await createTestComponent( + const { component } = await createTestComponent( { }} status={DOWNLOAD_STATUS.DOWNLOADED} />, - { store, history, apolloClient: client } + { store, apolloClient: client } ) + + testComponent = component }) it('download button renders', () => { @@ -57,9 +58,9 @@ describe('download button tests', () => { beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history + client = createClient(store) - testComponent = await createTestComponent( + const { component } = await createTestComponent( { }} status={DOWNLOAD_STATUS.DOWNLOADED} />, - { store, history, apolloClient: client } + { store, apolloClient: client } ) + + testComponent = component }) it('download button renders', () => { diff --git a/packages/client/src/components/interface/Navigation.test.tsx b/packages/client/src/components/interface/Navigation.test.tsx index 1a08cd527f7..459fb654ae4 100644 --- a/packages/client/src/components/interface/Navigation.test.tsx +++ b/packages/client/src/components/interface/Navigation.test.tsx @@ -23,12 +23,10 @@ import { createClient } from '@client/utils/apolloClient' import { OfficeHome } from '@client/views/OfficeHome/OfficeHome' import { merge } from 'lodash' import * as React from 'react' -import { - WORKQUEUE_TABS, - Navigation -} from '@client/components/interface/Navigation' +import { Navigation } from '@client/components/interface/Navigation' import { ReactWrapper } from 'enzyme' import { Mock, vi } from 'vitest' +import { Router } from '@sentry/react/types/types' const getItem = window.localStorage.getItem as Mock const mockFetchUserDetails = vi.fn() @@ -70,7 +68,7 @@ const nameObjNatlSysAdmin = { storage.getItem = vi.fn() storage.setItem = vi.fn() -let { store, history } = createStore() +let { store } = createStore() let client = createClient(store) describe('Navigation for national system admin related tests', () => { @@ -80,28 +78,15 @@ describe('Navigation for national system admin related tests', () => { merge(mockUserResponse, nameObjNatlSysAdmin) mockFetchUserDetails.mockReturnValue(mockUserResponse) queries.fetchUserDetails = mockFetchUserDetails - ;({ store, history } = createStore()) + ;({ store } = createStore()) client = createClient(store) getItem.mockReturnValue(natlSysAdminToken) await store.dispatch(checkAuth()) await flushPromises() - testComponent = await createTestComponent( - , - { store, history } - ) + const { component } = await createTestComponent(, { store }) + + testComponent = component }) it('Tabs loaded successfully including config tab', async () => { @@ -123,52 +108,32 @@ describe('Navigation for national system admin related tests', () => { describe('Navigation for Registration agent related tests', () => { let testComponent: ReactWrapper<{}, {}> - + let router: Router beforeEach(async () => { merge(mockUserResponse, nameObj) mockFetchUserDetails.mockReturnValue(mockUserResponse) queries.fetchUserDetails = mockFetchUserDetails - ;({ store, history } = createStore()) + ;({ store } = createStore()) client = createClient(store) getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) await flushPromises() - testComponent = await createTestComponent( - , - { store, history } + const { component, router: testRouter } = await createTestComponent( + , + { store } ) + router = testRouter + testComponent = component }) it('renders page with team and performance tab for registration agent', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } - ) - expect(testComponent.exists('#navigation_team')).toBeTruthy() - expect(testComponent.exists('#navigation_performance')).toBeTruthy() - expect(testComponent.exists('#navigation_config_main')).toBeFalsy() + const { component } = await createTestComponent(, { + store, + apolloClient: client + }) + expect(component.exists('#navigation_team')).toBeTruthy() + expect(component.exists('#navigation_performance')).toBeTruthy() + expect(component.exists('#navigation_config_main')).toBeFalsy() }) it('5 application tabs exists for registration agent', async () => { @@ -187,18 +152,19 @@ describe('Navigation for Registration agent related tests', () => { .hostNodes() .simulate('click') await flushPromises() - expect(window.location.href).toContain('readyForReview') + + expect(router.state.location.pathname).toContain('readyForReview') testComponent .find('#navigation_requiresUpdate') .hostNodes() .simulate('click') await flushPromises() - expect(window.location.href).toContain('requiresUpdate') + expect(router.state.location.pathname).toContain('requiresUpdate') testComponent.find('#navigation_approvals').hostNodes().simulate('click') await flushPromises() - expect(window.location.href).toContain('approvals') + expect(router.state.location.pathname).toContain('approvals') }) }) @@ -209,16 +175,18 @@ describe('Navigation for District Registrar related tests', () => { merge(mockUserResponse, nameObj) mockFetchUserDetails.mockReturnValue(mockUserResponse) queries.fetchUserDetails = mockFetchUserDetails - ;({ store, history } = createStore()) + ;({ store } = createStore()) client = createClient(store) getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) await flushPromises() - testComponent = await createTestComponent( + const { component } = await createTestComponent( {}} />, - { store, history } + { store } ) + + testComponent = component }) it('settings and logout exists on navigation mobile view', async () => { expect(testComponent.exists('#navigation_settings')).toBeTruthy() diff --git a/packages/client/src/components/interface/Navigation.tsx b/packages/client/src/components/interface/Navigation.tsx index beb2576480f..e0aefd52d3d 100644 --- a/packages/client/src/components/interface/Navigation.tsx +++ b/packages/client/src/components/interface/Navigation.tsx @@ -55,7 +55,10 @@ import * as React from 'react' import { injectIntl, WrappedComponentProps as IntlShapeProps } from 'react-intl' import { connect } from 'react-redux' import { IS_PROD_ENVIRONMENT } from '@client/utils/constants' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' import { stringify } from 'query-string' diff --git a/packages/client/src/components/review/RejectRegistrationForm.test.tsx b/packages/client/src/components/review/RejectRegistrationForm.test.tsx index ceb832787db..6f30d8c7357 100644 --- a/packages/client/src/components/review/RejectRegistrationForm.test.tsx +++ b/packages/client/src/components/review/RejectRegistrationForm.test.tsx @@ -17,14 +17,14 @@ import { EventType } from '@client/utils/gateway' import { createDeclaration } from '@client/declarations' import { vi } from 'vitest' -const { store, history } = createStore() +const { store } = createStore() const mockHandler = vi.fn() describe('reject registration form', () => { let component: ReactWrapper<{}, {}> const draftDeclaration = createDeclaration(EventType.Birth) beforeEach(async () => { - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { draftId="04ba2b0e-ba38-4049-ad74-332e4ee9fbfe" event={EventType.Birth} />, - { store, history } + { store } ) + component = testComponent }) it('renders form', () => { diff --git a/packages/client/src/components/review/RejectRegistrationForm.tsx b/packages/client/src/components/review/RejectRegistrationForm.tsx index 0a6a3121cfb..94a57c1bf13 100644 --- a/packages/client/src/components/review/RejectRegistrationForm.tsx +++ b/packages/client/src/components/review/RejectRegistrationForm.tsx @@ -35,7 +35,10 @@ import { isEmpty } from 'lodash' import * as React from 'react' import { injectIntl, WrappedComponentProps as IntlShapeProps } from 'react-intl' import { connect } from 'react-redux' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' import styled from 'styled-components' diff --git a/packages/client/src/index.tsx b/packages/client/src/index.tsx index ebf9e81b6c1..be169a8a920 100644 --- a/packages/client/src/index.tsx +++ b/packages/client/src/index.tsx @@ -8,28 +8,20 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { ErrorBoundary } from '@client/components/ErrorBoundary' -import { StyledErrorBoundary } from '@client/components/StyledErrorBoundary' -import { I18nContainer } from '@client/i18n/components/I18nContainer' -import { createGlobalStyle, ThemeProvider } from 'styled-components' -import { getTheme } from '@opencrvs/components/lib/theme' -import { useApolloClient } from '@client/utils/apolloClient' -import { Provider } from 'react-redux' -import { RouterProvider } from 'react-router-dom' -import { ApolloProvider } from '@client/utils/ApolloProvider' // eslint-disable-next-line import/no-unassigned-import import 'focus-visible/dist/focus-visible.js' -import * as React from 'react' -import { createRoot } from 'react-dom/client' -import { router } from '@client/App' -import { createStore } from '@client/store' import * as actions from '@client/notification/actions' import { storage } from '@client/storage' +import { createStore } from '@client/store' +import * as React from 'react' +import { createRoot } from 'react-dom/client' // eslint-disable-next-line no-restricted-imports -import * as Sentry from '@sentry/react' import { SubmissionController } from '@client/SubmissionController' -import WebFont from 'webfontloader' +import * as Sentry from '@sentry/react' import { BrowserTracing } from '@sentry/tracing' +import { createBrowserRouter } from 'react-router-dom' +import WebFont from 'webfontloader' +import { App, routesConfig } from './App' import { APPLICATION_VERSION } from './utils/constants' WebFont.load({ @@ -71,42 +63,8 @@ window.addEventListener('online', userReconnectedToast) const container = document.getElementById('root') const root = createRoot(container!) -// Injecting global styles for the body tag - used only once -// eslint-disable-line -const GlobalStyle = createGlobalStyle` - body { - margin: 0; - padding: 0; - overflow-y: scroll; - } -` - -/** - * Starting from react-router v6, routes need to be renderd 'on-the-side' of the application. - * This changes the order of how provider components are rendered. - * Root component is the entry point of the application, and renders all the providers before application components, which are rendered by the RouterProvider. - */ -export const Root = () => { - const { client } = useApolloClient(store) - - return ( - - - - - - - - - - - - - - - ) -} +const router = createBrowserRouter(routesConfig) -root.render() +root.render() new SubmissionController(store).start() diff --git a/packages/client/src/navigation/index.ts b/packages/client/src/navigation/index.ts index d17a77cb91e..b2d73cbe6f8 100644 --- a/packages/client/src/navigation/index.ts +++ b/packages/client/src/navigation/index.ts @@ -105,16 +105,6 @@ export function generatePerformanceHomeUrl({ } } -// @TODO: Check if format url does anything -// export function goToAdvancedSearchResult(mobile?: boolean) { -// return push(formatUrl(ADVANCED_SEARCH_RESULT, {})) -// } - -// @TODO: Delete after test -// export function goToSearch() { -// return push(SEARCH) -// } - export const generatePrintCertificateUrl = ({ registrationId, event, @@ -246,6 +236,7 @@ export const generateCompletenessRatesUrl = ({ time?: CompletenessRateTime }) => formatUrl(EVENT_COMPLETENESS_RATES, { eventType }) + + '?' + stringify( locationId ? { diff --git a/packages/client/src/profile/profileActions.ts b/packages/client/src/profile/profileActions.ts index 8dcd8291d00..4d0a4b1dc73 100644 --- a/packages/client/src/profile/profileActions.ts +++ b/packages/client/src/profile/profileActions.ts @@ -9,7 +9,6 @@ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { RouterAction } from 'connected-react-router' import { ApolloQueryResult } from '@apollo/client' import { FetchUserQuery } from '@client/utils/gateway' import { UserDetails } from '@client/utils/userUtils' @@ -178,7 +177,6 @@ export type Action = | CheckAuthAction | SetUserDetailsAction | RedirectToAuthenticationAction - | RouterAction | ISetInitialUserDetails | IGetStorageUserDetailsSuccessAction | IGetStorageUserDetailsFailedAction diff --git a/packages/client/src/setupTests.ts b/packages/client/src/setupTests.ts index 5050f0985f2..f986361115f 100644 --- a/packages/client/src/setupTests.ts +++ b/packages/client/src/setupTests.ts @@ -278,11 +278,3 @@ vi.mock('./utils', async () => ({ isNavigatorOnline: () => true, getUserRole: vi.fn().mockImplementation((lang, role) => 'ENTREPENEUR') })) - -vi.mock('react-router-dom', async () => ({ - ...((await vi.importActual('react-router-dom')) as any), - useParams: vi.fn().mockImplementation(() => ({ - event: 'birth', - section: 'child' - })) -})) diff --git a/packages/client/src/store.ts b/packages/client/src/store.ts index c3e9eff2ad8..b3d524ca99b 100644 --- a/packages/client/src/store.ts +++ b/packages/client/src/store.ts @@ -8,7 +8,7 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { createBrowserHistory, History } from 'history' +import { History } from 'history' import { AnyAction, applyMiddleware, diff --git a/packages/client/src/tests/util.tsx b/packages/client/src/tests/util.tsx index 49dd5ba32d1..28b101e5bf2 100644 --- a/packages/client/src/tests/util.tsx +++ b/packages/client/src/tests/util.tsx @@ -8,57 +8,57 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { App } from '@client/App' -import { EventType, SystemRoleType, Status } from '@client/utils/gateway' -import { UserDetails } from '@client/utils/userUtils' +import { + ApolloClient, + ApolloLink, + ApolloProvider, + InMemoryCache, + NetworkStatus, + Observable +} from '@apollo/client' +import { MockedProvider } from '@apollo/client/testing' +import { App, routesConfig } from '@client/App' import { getRegisterForm } from '@client/forms/register/declaration-selectors' import { getReviewForm } from '@client/forms/register/review-selectors' import { offlineDataReady, setOfflineData } from '@client/offline/actions' +import { setUserDetails } from '@client/profile/profileActions' import { AppStore, createStore, IStoreState } from '@client/store' -import { ThemeProvider } from 'styled-components' import { getSchema } from '@client/tests/graphql-schema-mock' +import { EventType, Status, SystemRoleType } from '@client/utils/gateway' +import { UserDetails } from '@client/utils/userUtils' import { I18nContainer } from '@opencrvs/client/src/i18n/components/I18nContainer' import { getTheme } from '@opencrvs/components/lib/theme' -import { join } from 'path' +import Adapter from '@wojtekmaj/enzyme-adapter-react-17' import { configure, mount, + MountRendererProps, ReactWrapper, - shallow, - MountRendererProps + shallow } from 'enzyme' -import Adapter from '@wojtekmaj/enzyme-adapter-react-17' import { readFileSync } from 'fs' import { graphql, print } from 'graphql' +import { createLocation, createMemoryHistory } from 'history' import * as jwt from 'jsonwebtoken' +import { join } from 'path' +import { stringify } from 'query-string' import * as React from 'react' -import { - ApolloProvider, - NetworkStatus, - ApolloClient, - InMemoryCache, - ApolloLink, - Observable -} from '@apollo/client' -import { MockedProvider } from '@apollo/client/testing' import { IntlShape } from 'react-intl' import { Provider } from 'react-redux' import { AnyAction, Store } from 'redux' +import { ThemeProvider } from 'styled-components' import { waitForElement } from './wait-for-element' -import { setUserDetails } from '@client/profile/profileActions' -import { createLocation, createMemoryHistory, History } from 'history' -import { stringify } from 'query-string' -import { ConnectedRouter } from 'connected-react-router' -import { mockOfflineData } from './mock-offline-data' -import { Section, SubmissionAction } from '@client/forms' import { SUBMISSION_STATUS } from '@client/declarations' -import { vi } from 'vitest' -import { getSystemRolesQuery } from '@client/forms/user/query/queries' +import { Section, SubmissionAction } from '@client/forms' +import { deserializeFormSection } from '@client/forms/deserializer/deserializer' import { createOrUpdateUserMutation } from '@client/forms/user/mutation/mutations' +import { getSystemRolesQuery } from '@client/forms/user/query/queries' import { draftToGqlTransformer } from '@client/transformer' -import { deserializeFormSection } from '@client/forms/deserializer/deserializer' import * as builtInValidators from '@client/utils/validate' +import { createMemoryRouter, RouterProvider } from 'react-router-dom' +import { vi } from 'vitest' +import { mockOfflineData } from './mock-offline-data' export const registerScopeToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsImNlcnRpZnkiLCJkZW1vIl0sImlhdCI6MTU0MjY4ODc3MCwiZXhwIjoxNTQzMjkzNTcwLCJhdWQiOlsib3BlbmNydnM6YXV0aC11c2VyIiwib3BlbmNydnM6dXNlci1tZ250LXVzZXIiLCJvcGVuY3J2czpoZWFydGgtdXNlciIsIm9wZW5jcnZzOmdhdGV3YXktdXNlciIsIm9wZW5jcnZzOm5vdGlmaWNhdGlvbi11c2VyIiwib3BlbmNydnM6d29ya2Zsb3ctdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1YmVhYWY2MDg0ZmRjNDc5MTA3ZjI5OGMifQ.ElQd99Lu7WFX3L_0RecU_Q7-WZClztdNpepo7deNHqzro-Cog4WLN7RW3ZS5PuQtMaiOq1tCb-Fm3h7t4l4KDJgvC11OyT7jD6R2s2OleoRVm3Mcw5LPYuUVHt64lR_moex0x_bCqS72iZmjrjS-fNlnWK5zHfYAjF2PWKceMTGk6wnI9N49f6VwwkinJcwJi6ylsjVkylNbutQZO0qTc7HRP-cBfAzNcKD37FqTRNpVSvHdzQSNcs7oiv3kInDN5aNa2536XSd3H-RiKR9hm9eID9bSIJgFIGzkWRd5jnoYxT70G0t03_mTVnDnqPXDtyI-lmerx24Ost0rQLUNIg' @@ -144,17 +144,20 @@ export function waitForReady(app: ReactWrapper) { } export async function createTestApp( - config = { waitUntilOfflineCountryConfigLoaded: true } + config = { waitUntilOfflineCountryConfigLoaded: true }, + initialEntries?: string[] ) { - const { store, history } = await createTestStore() + const { store } = await createTestStore() + const router = createMemoryRouter(routesConfig, { initialEntries }) + const app = mount( - + ) if (config.waitUntilOfflineCountryConfigLoaded) { await waitForReady(app) } - return { history, app, store } + return { app, store, router } } interface ITestView { @@ -847,24 +850,37 @@ export const mockOfflineDataDispatch = { } export async function createTestStore() { - const { store, history } = createStore() + const { store } = createStore() store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() // This is to resolve the `referenceApi.importValidators()` promise - return { store, history } + return { store } } export async function createTestComponent( node: React.ReactElement, { store, - history, graphqlMocks, - apolloClient + apolloClient, + initialEntries, + path = '*' }: { store: AppStore - history: History graphqlMocks?: MockedProvider['props']['mocks'] apolloClient?: ApolloClient + initialEntries?: + | string[] + | { + pathname: string + state: Record< + string, + | string + | boolean + | number + | Record + > + }[] + path?: string }, options?: MountRendererProps ) { @@ -889,22 +905,38 @@ export async function createTestComponent( ) } + const router = createMemoryRouter( + [ + { + path, + element: node + } + ], + { initialEntries } + ) - function PropProxy(props: Record) { + function PropProxy() { return withGraphQL( - - - - - - - + + + + + ) } - return mount(, options) + return { component: mount(, options), router } +} + +/** + * Create a test component with the given node and store. + * Returns component route + */ +export type TestComponentWithRouteMock = { + component: ReactWrapper<{}, {}> + router: Awaited>['router'] } export const getFileFromBase64String = ( @@ -961,6 +993,11 @@ export async function goToMotherSection(component: ReactWrapper) { await waitForElement(component, '#form_section_id_mother-view-group') } +export async function goToChildSection(component: ReactWrapper) { + await goToSection(component, 1) + await waitForElement(component, '#form_section_id_child-view-group') +} + export async function getRegisterFormFromStore( store: Store, event: EventType @@ -1065,7 +1102,7 @@ export function createRouterProps< if (search) { location.search = stringify(search) } - const match: Params = { + const match = { isExact: false, path, url: path, diff --git a/packages/client/src/transformer/transformer.test.tsx b/packages/client/src/transformer/transformer.test.tsx index 6d293c251df..41984ce00fe 100644 --- a/packages/client/src/transformer/transformer.test.tsx +++ b/packages/client/src/transformer/transformer.test.tsx @@ -23,8 +23,6 @@ import { IDeclaration, SUBMISSION_STATUS } from '@client/declarations' -import { ReactWrapper } from 'enzyme' -import { History } from 'history' import { Store } from 'redux' import { v4 as uuid } from 'uuid' import { draftToGqlTransformer } from '@client/transformer' @@ -36,13 +34,12 @@ import { clone } from 'lodash' import { birthDraftData } from '@client/tests/mock-drafts' import createFetchMock from 'vitest-fetch-mock' import { vi } from 'vitest' +import { formatUrl } from '@client/navigation' const fetch = createFetchMock(vi) fetch.enableMocks() describe('when draft data is transformed to graphql', () => { - let app: ReactWrapper - let history: History let store: Store let customDraft: IDeclaration let form: IForm @@ -55,13 +52,6 @@ describe('when draft data is transformed to graphql', () => { [JSON.stringify({ data: mockOfflineData.locations }), { status: 200 }], [JSON.stringify({ data: mockOfflineData.facilities }), { status: 200 }] ) - const testApp = await createTestApp() - app = testApp.app - await flushPromises() - app.update() - history = testApp.history - store = testApp.store - store.dispatch(getOfflineDataSuccess(JSON.stringify(mockOfflineData))) customDraft = { id: uuid(), @@ -69,16 +59,24 @@ describe('when draft data is transformed to graphql', () => { event: EventType.Birth, submissionStatus: SUBMISSION_STATUS[SUBMISSION_STATUS.DRAFT] } - store.dispatch(storeDeclaration(customDraft)) - form = getRegisterForm(store.getState())[EventType.Birth] - history.replace( - DRAFT_BIRTH_PARENT_FORM.replace( - ':declarationId', - customDraft.id.toString() - ) + + // @TODO: Check if this is even needed? + const testApp = await createTestApp( + { waitUntilOfflineCountryConfigLoaded: false }, + [ + formatUrl(DRAFT_BIRTH_PARENT_FORM, { + declarationId: customDraft.id.toString() + }) + ] ) - app.update() + await flushPromises() + + store = testApp.store + store.dispatch(getOfflineDataSuccess(JSON.stringify(mockOfflineData))) + + store.dispatch(storeDeclaration(customDraft)) + form = getRegisterForm(store.getState())[EventType.Birth] }) describe('when user is in birth registration by parent informant view', () => { @@ -106,6 +104,7 @@ describe('when draft data is transformed to graphql', () => { ).eventLocation.type ).toBe('PRIVATE_HOME') }) + it('Pass false as detailsExist on father section', () => { const data = { child: birthDraftData.child, @@ -138,6 +137,7 @@ describe('when draft data is transformed to graphql', () => { ).registration.inCompleteFields ).toContain('father/father-view-group/reasonNotApplying') }) + it('Sends inCompleteFields if in-complete data is given', () => { const data = { child: {}, @@ -156,6 +156,7 @@ describe('when draft data is transformed to graphql', () => { ).registration.inCompleteFields ).toContain('child/child-view-group/placeOfBirth') }) + it('Sends inCompleteFields when registration data is also missing', () => { const data = { child: {}, diff --git a/packages/client/src/user/userReducer.ts b/packages/client/src/user/userReducer.ts index 4cadd75e9f4..ed8e50510ac 100644 --- a/packages/client/src/user/userReducer.ts +++ b/packages/client/src/user/userReducer.ts @@ -105,6 +105,7 @@ interface IUserFormDataSubmitAction { variables: { [key: string]: any } isUpdate: boolean officeLocationId: string + onSuccess: () => void } } @@ -113,7 +114,8 @@ export function submitUserFormData( mutation: any, variables: { [key: string]: any }, officeLocationId: string, - isUpdate = false + isUpdate = false, + onSuccess: () => void ): IUserFormDataSubmitAction { return { type: SUBMIT_USER_FORM_DATA, @@ -122,7 +124,8 @@ export function submitUserFormData( mutation, variables, officeLocationId, - isUpdate + isUpdate, + onSuccess } } } @@ -137,14 +140,19 @@ interface ISubmitSuccessAction { type: typeof SUBMIT_USER_FORM_DATA_SUCCESS payload: { isUpdate: boolean + onSuccess: () => void } } -export function submitSuccess(isUpdate = false): ISubmitSuccessAction { +export function submitSuccess( + isUpdate: boolean, + onSuccess: () => void +): ISubmitSuccessAction { return { type: SUBMIT_USER_FORM_DATA_SUCCESS, payload: { - isUpdate + isUpdate: !!isUpdate, + onSuccess } } } @@ -356,7 +364,8 @@ export const userFormReducer: LoopReducer = ( ] }), { - successActionCreator: () => submitSuccess(isUpdate), + successActionCreator: () => + submitSuccess(isUpdate, action.payload.onSuccess), failActionCreator: submitFail } ) @@ -372,14 +381,18 @@ export const userFormReducer: LoopReducer = ( ) case SUBMIT_USER_FORM_DATA_SUCCESS: - const list = Cmd.list>([ + const list = Cmd.list< + | ReturnType + | ReturnType + >([ Cmd.action( showSubmitFormSuccessToast( action.payload.isUpdate ? TOAST_MESSAGES.UPDATE_SUCCESS : TOAST_MESSAGES.SUCCESS ) - ) + ), + Cmd.action(clearUserFormData()) ]) return loop({ ...state, submitting: false, submissionError: false }, list) diff --git a/packages/client/src/v2-events/features/events/PublishEvent.tsx b/packages/client/src/v2-events/features/events/PublishEvent.tsx index c84eddccc1e..037e7ea36e9 100644 --- a/packages/client/src/v2-events/features/events/PublishEvent.tsx +++ b/packages/client/src/v2-events/features/events/PublishEvent.tsx @@ -23,8 +23,9 @@ import { useParams } from 'react-router-dom' export function PublishEvent() { const { eventType } = useParams<{ eventType: string }>() - const { title, exit, saveAndExit, previous, next, finish } = - useEvent(eventType) + const { title, exit, saveAndExit, previous, next, finish } = useEvent( + eventType! + ) return ( { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History beforeEach(async () => { - const s = createStore() - store = s.store - history = s.history - component = await createTestComponent( - // @ts-ignore - , - { - store, - history, - graphqlMocks: graphqlMock as any - } - ) + ;({ store } = createStore()) - await flushPromises() - component.update() store.dispatch( setAdvancedSearchParam({ ...advancedSearchInitialState, @@ -175,9 +155,15 @@ describe('AdvancedSearchResult Bookmark', () => { registrationStatuses: ['IN_PROGRESS'] }) ) - component.update() + store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - component.update() + ;({ component } = await createTestComponent(, { + store, + initialEntries: [ADVANCED_SEARCH_RESULT], + path: ADVANCED_SEARCH_RESULT, + graphqlMocks: graphqlMock as any + })) + await waitForElement(component, 'AdvancedSearchResultComp') }) @@ -244,10 +230,7 @@ describe('AdvancedSearchResult Bookmark', () => { .find('#bookmark_advanced_search_result') .hostNodes() .simulate('click') - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) + await flushPromises() component.update() expect( @@ -256,6 +239,8 @@ describe('AdvancedSearchResult Bookmark', () => { }) it('should remove bookmark advanced search & show notification if click on confirm button', async () => { + await flushPromises() + store.dispatch( setAdvancedSearchParam({ ...advancedSearchInitialState, @@ -273,10 +258,7 @@ describe('AdvancedSearchResult Bookmark', () => { .find('#remove_advanced_search_bookmark') .hostNodes() .simulate('click') - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) + await flushPromises() component.update() expect( diff --git a/packages/client/src/views/AdvancedSearch/AdvancedSearchResult.tsx b/packages/client/src/views/AdvancedSearch/AdvancedSearchResult.tsx index 400f5578dd9..7ea99d4b713 100644 --- a/packages/client/src/views/AdvancedSearch/AdvancedSearchResult.tsx +++ b/packages/client/src/views/AdvancedSearch/AdvancedSearchResult.tsx @@ -42,7 +42,10 @@ import { SearchEventsQuery } from '@client/utils/gateway' import { Frame } from '@opencrvs/components/lib/Frame' import { LoadingIndicator } from '@client/views/OfficeHome/LoadingIndicator' import { Navigate, useNavigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { ErrorText, Link, Pill } from '@client/../../components/lib' import { WQContentWrapper } from '@client/views/OfficeHome/WQContentWrapper' import { diff --git a/packages/client/src/views/CorrectionForm/CorrectionForm.tsx b/packages/client/src/views/CorrectionForm/CorrectionForm.tsx index 39a87a161a1..282b7dff34a 100644 --- a/packages/client/src/views/CorrectionForm/CorrectionForm.tsx +++ b/packages/client/src/views/CorrectionForm/CorrectionForm.tsx @@ -12,7 +12,10 @@ import * as React from 'react' import { connect } from 'react-redux' import { IStoreState } from '@client/store' import { Navigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { IDeclaration, modifyDeclaration } from '@client/declarations' import { CorrectorForm, diff --git a/packages/client/src/views/CorrectionForm/CorrectionReasonForm.test.tsx b/packages/client/src/views/CorrectionForm/CorrectionReasonForm.test.tsx index b4f5e4ba18a..b582c0779d8 100644 --- a/packages/client/src/views/CorrectionForm/CorrectionReasonForm.test.tsx +++ b/packages/client/src/views/CorrectionForm/CorrectionReasonForm.test.tsx @@ -12,9 +12,9 @@ import { createStore } from '@client/store' import { createTestComponent, mockDeclarationData, - createRouterProps + TestComponentWithRouteMock } from '@client/tests/util' -import { ReactWrapper } from 'enzyme' + import * as React from 'react' import { CorrectionSection } from '@client/forms' import { EventType } from '@client/utils/gateway' @@ -24,7 +24,7 @@ import { formatUrl } from '@client/navigation' import { CERTIFICATE_CORRECTION } from '@client/navigation/routes' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' -let wrapper: ReactWrapper<{}, {}> +let wrapper: TestComponentWithRouteMock const birthDeclaration: IDeclaration = { id: '72c18939-70c1-40b4-9b80-b162c4871160', @@ -32,81 +32,70 @@ const birthDeclaration: IDeclaration = { event: EventType.Birth } -const { store, history } = createStore() +const { store } = createStore() describe('Correction reason form', () => { describe('for an declaration', () => { beforeEach(async () => { store.dispatch(storeDeclaration(birthDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + wrapper = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: birthDeclaration.id, + pageId: CorrectionSection.Reason + }) + ] + }) }) it('should disable the continue button if no reason is selected', () => { expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should not disable the continue button if a reason is selected', () => { - wrapper + wrapper.component .find('#type_CLERICAL_ERROR') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should to go summary page', () => { - wrapper + wrapper.component .find('#type_CLERICAL_ERROR') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should disable the continue button if other option is selected without specifying the reason', () => { - wrapper + wrapper.component .find('#type_OTHER') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should not disable the continue button if other option is selected with the reason specified', () => { - wrapper + wrapper.component .find('#type_OTHER') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() - wrapper + wrapper.component .find('input[name="type.nestedFields.otherReason"]') .simulate('change', { target: { @@ -114,18 +103,20 @@ describe('Correction reason form', () => { value: 'Misspelling' } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should cancel the correction when the cross button is pressed', () => { - wrapper.find('#crcl-btn').hostNodes().simulate('click') - wrapper.update() + wrapper.component.find('#crcl-btn').hostNodes().simulate('click') + wrapper.component.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.readyForReview) + expect(wrapper.router.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) }) }) diff --git a/packages/client/src/views/CorrectionForm/CorrectionSummary.test.tsx b/packages/client/src/views/CorrectionForm/CorrectionSummary.test.tsx index 28c6f61c8d8..27e437ef0e0 100644 --- a/packages/client/src/views/CorrectionForm/CorrectionSummary.test.tsx +++ b/packages/client/src/views/CorrectionForm/CorrectionSummary.test.tsx @@ -12,7 +12,6 @@ import { createStore } from '@client/store' import { createTestComponent, mockDeclarationData, - createRouterProps, flushPromises, mockDeathDeclarationData, getRegisterFormFromStore, @@ -35,8 +34,7 @@ import { REQUEST_REG_CORRECTION } from '@client/forms/correction/mutations' import { draftToGqlTransformer } from '@client/transformer' import { getOfflineDataSuccess } from '@client/offline/actions' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' - -let wrapper: ReactWrapper<{}, {}> +import { Router } from '@sentry/react/types/types' const deathDeclaration: IDeclaration = { id: '85bccf72-6117-4cab-827d-47728becb0c1', @@ -165,7 +163,10 @@ const birthDeclaration: IDeclaration = { timeLoggedMS: 990618 } -const { store, history } = createStore() +const { store } = createStore() + +let wrapper: ReactWrapper<{}, {}> +let router: Router describe('Correction summary', () => { describe('for a birth declaration', () => { @@ -174,25 +175,17 @@ describe('Correction summary', () => { await flushPromises() store.dispatch(storeDeclaration(birthDeclaration)) const form = await getRegisterFormFromStore(store, EventType.Birth) - wrapper = await createTestComponent( - , + { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ formatUrl(CERTIFICATE_CORRECTION, { declarationId: birthDeclaration.id, pageId: CorrectionSection.Summary - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - declarationId: birthDeclaration.id, - pageId: CorrectionSection.Summary - } - } - )} - />, - { - store, - history, + }) + ], graphqlMocks: [ { request: { @@ -214,6 +207,8 @@ describe('Correction summary', () => { ] } ) + router = testRouter + wrapper = component }) it('should disable the mark correction button if fees no is selected', () => { expect( @@ -380,7 +375,7 @@ describe('Correction summary', () => { await flushPromises() wrapper.update() - expect(history.location.pathname).toContain('/review-view-group') + expect(router.state.location.pathname).toContain('/review-view-group') }) it('should cancel the correction when the cross button is pressed', () => { @@ -388,48 +383,39 @@ describe('Correction summary', () => { wrapper.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.readyForReview) + expect(router.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) - it('after successful correction request redirects to reg home review tab', () => { + it('after successful correction request redirects to reg home review tab', () => { wrapper .find('#correctionFees_NOT_REQUIRED') .hostNodes() .simulate('change', { target: { checked: true } }) wrapper.update() wrapper.find('#make_correction').hostNodes().simulate('click') + wrapper.find('#send').hostNodes().simulate('click') wrapper.update() - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( `registration-home/${WORKQUEUE_TABS.readyForReview}` ) }) }) describe('for a death declaration', () => { beforeEach(async () => { - // ;(deathDeclaration.data.corrector.relationship as any).value = 'INFORMANT' - store.dispatch(storeDeclaration(deathDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + const { component } = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: deathDeclaration.id, + pageId: CorrectionSection.Summary + }) + ] + }) + wrapper = component }) it('should return corrector informat', () => { const instance = wrapper diff --git a/packages/client/src/views/CorrectionForm/CorrectionSummary.tsx b/packages/client/src/views/CorrectionForm/CorrectionSummary.tsx index 7d20e6679eb..ddecd8c2ae4 100644 --- a/packages/client/src/views/CorrectionForm/CorrectionSummary.tsx +++ b/packages/client/src/views/CorrectionForm/CorrectionSummary.tsx @@ -83,7 +83,10 @@ import { UserDetails } from '@client/utils/userUtils' import { ROLE_REGISTRATION_AGENT } from '@client/utils/constants' import { Dialog } from '@opencrvs/components/lib/Dialog/Dialog' import { SystemRoleType } from '@client/utils/gateway' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' const SupportingDocument = styled.div` display: flex; diff --git a/packages/client/src/views/CorrectionForm/CorrectorForm.test.tsx b/packages/client/src/views/CorrectionForm/CorrectorForm.test.tsx index 7f9040ba2e2..27db28bdb32 100644 --- a/packages/client/src/views/CorrectionForm/CorrectorForm.test.tsx +++ b/packages/client/src/views/CorrectionForm/CorrectorForm.test.tsx @@ -13,9 +13,9 @@ import { createTestComponent, mockDeclarationData, mockDeathDeclarationData, - createRouterProps + TestComponentWithRouteMock } from '@client/tests/util' -import { ReactWrapper } from 'enzyme' + import * as React from 'react' import { CorrectorForm } from './CorrectorForm' import { CorrectionSection } from '@client/forms' @@ -26,7 +26,7 @@ import { formatUrl } from '@client/navigation' import { CERTIFICATE_CORRECTION } from '@client/navigation/routes' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' -let wrapper: ReactWrapper<{}, {}> +let wrapper: TestComponentWithRouteMock const birthDeclaration: IDeclaration = { id: '72c18939-70c1-40b4-9b80-b162c4871160', @@ -40,56 +40,47 @@ const deathDeclaration: IDeclaration = { event: EventType.Death } -const { store, history } = createStore() +const { store } = createStore() describe('Corrector form', () => { describe('for a birth registration', () => { beforeEach(async () => { store.dispatch(storeDeclaration(birthDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + + // NOTE this is different component than **CorrectorForm** + wrapper = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: birthDeclaration.id, + pageId: CorrectionSection.Corrector + }) + ] + }) }) it('should disable the continue button if no option is selected', () => { expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should not disable the continue button if an option is selected', () => { - wrapper + wrapper.component .find('#relationship_FATHER') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should go to verify section', () => { - wrapper.find('#confirm_form').hostNodes().simulate('click') - wrapper.update() - expect(history.location.pathname).toContain('/verify/father') + wrapper.component.find('#confirm_form').hostNodes().simulate('click') + wrapper.component.update() + expect(wrapper.router.state.location.pathname).toContain('/verify/father') }) }) describe('for a birth registration with father details', () => { @@ -108,12 +99,21 @@ describe('Corrector form', () => { , { store, - history + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: birthDeclaration.id, + pageId: CorrectionSection.Corrector + }) + ] } ) }) + it('should show the father option', () => { - expect(wrapper.find('#relationship_FATHER').hostNodes()).toHaveLength(1) + expect( + wrapper.component.find('#relationship_FATHER').hostNodes() + ).toHaveLength(1) }) }) @@ -132,56 +132,44 @@ describe('Corrector form', () => { wrapper = await createTestComponent( , { - store, - history + store } ) }) it('should not show the father option', () => { - expect(wrapper.exists('#relationship_FATHER')).toBeFalsy() + expect(wrapper.component.exists('#relationship_FATHER')).toBeFalsy() }) }) describe('for a death registration', () => { beforeEach(async () => { store.dispatch(storeDeclaration(deathDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + wrapper = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: deathDeclaration.id, + pageId: CorrectionSection.Corrector + }) + ] + }) }) it('should disable the continue button if no option is selected', () => { expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should not disable the continue button if an option is selected', () => { - wrapper + wrapper.component .find('#relationship_INFORMANT_SPOUSE') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) }) @@ -189,48 +177,37 @@ describe('Corrector form', () => { describe('for an declaration', () => { beforeEach(async () => { store.dispatch(storeDeclaration(birthDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + wrapper = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: birthDeclaration.id, + pageId: CorrectionSection.Corrector + }) + ] + }) }) it('should disable the continue button if others option is selected without specifying the relationship', () => { - wrapper + wrapper.component .find('#relationship_OTHER') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should not disable the continue button if others option is selected with the relationship specified', () => { - wrapper + wrapper.component .find('#relationship_OTHER') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() - wrapper + wrapper.component .find('input[name="relationship.nestedFields.otherRelationship"]') .simulate('change', { target: { @@ -238,18 +215,20 @@ describe('Corrector form', () => { value: 'Grandma' } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should cancel the correction when the cross button is pressed', () => { - wrapper.find('#crcl-btn').hostNodes().simulate('click') - wrapper.update() + wrapper.component.find('#crcl-btn').hostNodes().simulate('click') + wrapper.component.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.readyForReview) + expect(wrapper.router.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) }) }) diff --git a/packages/client/src/views/CorrectionForm/ReviewForm.test.tsx b/packages/client/src/views/CorrectionForm/ReviewForm.test.tsx index f6ee96218f0..3735b839042 100644 --- a/packages/client/src/views/CorrectionForm/ReviewForm.test.tsx +++ b/packages/client/src/views/CorrectionForm/ReviewForm.test.tsx @@ -11,7 +11,8 @@ import { mockDeclarationData, createTestApp, - flushPromises + flushPromises, + TestComponentWithRouteMock } from '@client/tests/util' import { ReactWrapper } from 'enzyme' import { ReviewSection } from '@client/forms' @@ -25,13 +26,12 @@ import { import { formatUrl } from '@client/navigation' import { CERTIFICATE_CORRECTION_REVIEW } from '@client/navigation/routes' import { Store } from 'redux' -import { History } from 'history' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { waitForElement } from '@client/tests/wait-for-element' let wrapper: ReactWrapper<{}, {}> let store: Store -let history: History +let router: TestComponentWithRouteMock['router'] const declaration: IDeclaration = createReviewDeclaration( '72c18939-70c1-40b4-9b80-b162c4871160', @@ -59,21 +59,29 @@ declaration.data.registration = { describe('Review form for an declaration', () => { beforeEach(async () => { - const appBundle = await createTestApp() + const appBundle = await createTestApp(undefined, [ + formatUrl(CERTIFICATE_CORRECTION_REVIEW, { + declarationId: declaration.id, + pageId: ReviewSection.Review, + groupId: 'review-view-group' + }) + ]) wrapper = appBundle.app store = appBundle.store - history = appBundle.history + router = appBundle.router store.dispatch(storeDeclaration(declaration)) - history.replace( + router.navigate( formatUrl(CERTIFICATE_CORRECTION_REVIEW, { declarationId: declaration.id, pageId: ReviewSection.Review, groupId: 'review-view-group' - }) + }), + { replace: true } ) + await waitForElement(wrapper, 'CorrectionReviewFormComponent') }) @@ -100,7 +108,7 @@ describe('Review form for an declaration', () => { wrapper.find('#exit-btn').hostNodes().simulate('click') wrapper.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.inProgress) + expect(router.state.location.pathname).toContain(WORKQUEUE_TABS.inProgress) }) it('should disable the continue button if no changes have been made', async () => { @@ -150,6 +158,6 @@ describe('Review form for an declaration', () => { wrapper.find('#continue_button').hostNodes().simulate('click') wrapper.update() - expect(history.location.pathname).toContain('/supportingDocuments') + expect(router.state.location.pathname).toContain('/supportingDocuments') }) }) diff --git a/packages/client/src/views/CorrectionForm/ReviewForm.tsx b/packages/client/src/views/CorrectionForm/ReviewForm.tsx index a604c994af7..947f9f975b4 100644 --- a/packages/client/src/views/CorrectionForm/ReviewForm.tsx +++ b/packages/client/src/views/CorrectionForm/ReviewForm.tsx @@ -18,7 +18,10 @@ import { connect } from 'react-redux' import { getEventReviewForm } from '@client/forms/register/review-selectors' import { EventType } from '@client/utils/gateway' import { Navigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' type IStateProps = { declaration: IDeclaration | undefined diff --git a/packages/client/src/views/CorrectionForm/SupportingDocumentsForm.test.tsx b/packages/client/src/views/CorrectionForm/SupportingDocumentsForm.test.tsx index 4d9dc95d06d..35fe0ac0e92 100644 --- a/packages/client/src/views/CorrectionForm/SupportingDocumentsForm.test.tsx +++ b/packages/client/src/views/CorrectionForm/SupportingDocumentsForm.test.tsx @@ -10,11 +10,11 @@ */ import { createStore } from '@client/store' import { - createRouterProps, createTestComponent, - mockDeclarationData + mockDeclarationData, + TestComponentWithRouteMock } from '@client/tests/util' -import { ReactWrapper } from 'enzyme' + import * as React from 'react' import { CorrectionSection } from '@client/forms' import { EventType } from '@client/utils/gateway' @@ -24,7 +24,7 @@ import { CERTIFICATE_CORRECTION } from '@client/navigation/routes' import { CorrectionForm } from './CorrectionForm' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' -let wrapper: ReactWrapper<{}, {}> +let wrapper: TestComponentWithRouteMock const birthDeclaration: IDeclaration = { id: '72c18939-70c1-40b4-9b80-b162c4871160', @@ -32,53 +32,44 @@ const birthDeclaration: IDeclaration = { event: EventType.Birth } -const { store, history } = createStore() +const { store } = createStore() describe('for an declaration', () => { beforeEach(async () => { store.dispatch(storeDeclaration(birthDeclaration)) - wrapper = await createTestComponent( - , - { - store, - history - } - ) + wrapper = await createTestComponent(, { + store, + path: CERTIFICATE_CORRECTION, + initialEntries: [ + formatUrl(CERTIFICATE_CORRECTION, { + declarationId: birthDeclaration.id, + pageId: CorrectionSection.SupportingDocuments + }) + ] + }) }) it('should disable the continue button', () => { expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeTruthy() }) it('should enable the continue button if any radio button is selected', () => { - wrapper + wrapper.component .find('#supportDocumentRequiredForCorrection_true') .hostNodes() .simulate('change', { target: { checked: true } }) - wrapper.update() + wrapper.component.update() expect( - wrapper.find('#confirm_form').hostNodes().props().disabled + wrapper.component.find('#confirm_form').hostNodes().props().disabled ).toBeFalsy() }) it('should goto home if cross button is pressed', () => { - wrapper.find('#crcl-btn').hostNodes().simulate('click') - wrapper.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.readyForReview) + wrapper.component.find('#crcl-btn').hostNodes().simulate('click') + wrapper.component.update() + expect(wrapper.router.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) }) diff --git a/packages/client/src/views/CorrectionForm/VerifyCorrector.test.tsx b/packages/client/src/views/CorrectionForm/VerifyCorrector.test.tsx index 3a4fd795d9b..dff0f8d16bd 100644 --- a/packages/client/src/views/CorrectionForm/VerifyCorrector.test.tsx +++ b/packages/client/src/views/CorrectionForm/VerifyCorrector.test.tsx @@ -14,17 +14,19 @@ import { createTestComponent, flushPromises, mockDeclarationData, - mockDeathDeclarationData + mockDeathDeclarationData, + TestComponentWithRouteMock } from '@client/tests/util' import { VerifyCorrector } from './VerifyCorrector' import { storeDeclaration } from '@client/declarations' import { EventType } from '@client/utils/gateway' -import { ReactWrapper } from 'enzyme' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { vi } from 'vitest' +import { formatUrl } from '@client/navigation' +import { VERIFY_CORRECTOR } from '@client/navigation/routes' describe('verify corrector tests', () => { - const { store, history } = createStore() + const { store } = createStore() const birthDeclaration = { id: 'mockBirth1234', @@ -44,63 +46,55 @@ describe('verify corrector tests', () => { }) it('when mother is corrector renders idVerifier component', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + formatUrl(VERIFY_CORRECTOR, { declarationId: 'mockBirth1234', corrector: 'mother' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) }) it('when child is corrector renders idVerifier component', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + formatUrl(VERIFY_CORRECTOR, { declarationId: 'mockBirth1234', corrector: 'child' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) }) it('should takes user go back', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + '/', + formatUrl(VERIFY_CORRECTOR, { declarationId: 'mockBirth1234', corrector: 'mother' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) testComponent @@ -112,152 +106,152 @@ describe('verify corrector tests', () => { testComponent.update() - expect(history.location.pathname).toBe('/') + expect(router.state.location.pathname).toBe('/') }) }) describe('when father is corrector', () => { - let testComponent: ReactWrapper + let testComponent: TestComponentWithRouteMock beforeEach(async () => { - testComponent = await createTestComponent( - , - { store, history } - ) + testComponent = await createTestComponent(, { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + formatUrl(VERIFY_CORRECTOR, { + declarationId: 'mockBirth1234', + corrector: 'father' + }) + ] + }) }) it('renders idVerifier compomnent', () => { - expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) + expect( + testComponent.component.find('#idVerifier').hostNodes() + ).toHaveLength(1) }) it('clicking on yes button takes user to review certificate', () => { const date = new Date(243885600000) vi.setSystemTime(date) - testComponent + testComponent.component .find('#idVerifier') .find('#verifyPositive') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - expect(history.location.pathname).not.toContain('/verify') + expect(testComponent.router.state.location.pathname).not.toContain( + '/verify' + ) }) it('clicking on cancel button hides the modal', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - testComponent + testComponent.component .find('#withoutVerificationPrompt') .find('#cancel') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#withoutVerificationPrompt').hostNodes() + testComponent.component.find('#withoutVerificationPrompt').hostNodes() ).toHaveLength(0) }) it('clicking on Confirm button and go to review', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - testComponent + testComponent.component .find('#withoutVerificationPrompt') .find('#send') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - expect(history.location.pathname).toContain('/review-view-group') + expect(testComponent.router.state.location.pathname).toContain( + '/review-view-group' + ) }) it('go to review page', () => { - testComponent.find('#crcl-btn').hostNodes().simulate('click') + testComponent.component.find('#crcl-btn').hostNodes().simulate('click') - testComponent.update() + testComponent.component.update() - expect(history.location.pathname).toContain(WORKQUEUE_TABS.readyForReview) + expect(testComponent.router.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) }) describe('in case correction is not father, mother, child or informant', () => { - let testComponent: ReactWrapper + let testComponent: TestComponentWithRouteMock beforeEach(async () => { - testComponent = await createTestComponent( - , - { store, history } - ) + testComponent = await createTestComponent(, { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + formatUrl(VERIFY_CORRECTOR, { + declarationId: 'mockBirth1234', + corrector: 'other' + }) + ] + }) }) it('renders idVerifier compomnent', () => { - expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) + expect( + testComponent.component.find('#idVerifier').hostNodes() + ).toHaveLength(1) }) it('clicking on yes button takes user to review certificate', () => { const date = new Date(243885600000) vi.setSystemTime(date) - testComponent + testComponent.component .find('#idVerifier') .find('#verifyPositive') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - expect(history.location.pathname).not.toContain('/verify') + expect(testComponent.router.state.location.pathname).not.toContain( + '/verify' + ) }) it('clicking on no button shows up modal', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#withoutVerificationPrompt').hostNodes() + testComponent.component.find('#withoutVerificationPrompt').hostNodes() ).toHaveLength(1) }) }) @@ -268,21 +262,18 @@ describe('verify corrector tests', () => { }) it('when informant is corrector renders idVerifier component', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: VERIFY_CORRECTOR, + initialEntries: [ + formatUrl(VERIFY_CORRECTOR, { declarationId: 'mockDeath1234', corrector: 'informant' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) diff --git a/packages/client/src/views/CorrectionForm/VerifyCorrector.tsx b/packages/client/src/views/CorrectionForm/VerifyCorrector.tsx index 9a85e61668d..afef6adbb6b 100644 --- a/packages/client/src/views/CorrectionForm/VerifyCorrector.tsx +++ b/packages/client/src/views/CorrectionForm/VerifyCorrector.tsx @@ -31,7 +31,10 @@ import * as React from 'react' import { WrappedComponentProps as IntlShapeProps, injectIntl } from 'react-intl' import { connect } from 'react-redux' import { Navigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { CERTIFICATE_CORRECTION_REVIEW, REGISTRAR_HOME_TAB diff --git a/packages/client/src/views/Duplicates/DuplicateWarning.test.tsx b/packages/client/src/views/Duplicates/DuplicateWarning.test.tsx index b9a6b63c0a0..71fa75dea1d 100644 --- a/packages/client/src/views/Duplicates/DuplicateWarning.test.tsx +++ b/packages/client/src/views/Duplicates/DuplicateWarning.test.tsx @@ -49,10 +49,10 @@ describe('Review Duplicates component', () => { ] it('should load the duplicate warning component correctly', async () => { - const { store, history } = createStore() - const testComponent = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock } + { store, graphqlMocks: graphqlMock } ) const warning = await waitForElement(testComponent, Alert) diff --git a/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssueCollectorForm.test.tsx b/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssueCollectorForm.test.tsx index 14a6f6c6670..424dd833efa 100644 --- a/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssueCollectorForm.test.tsx +++ b/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssueCollectorForm.test.tsx @@ -10,16 +10,19 @@ */ import React from 'react' import { AppStore, createStore } from '@client/store' -import { createLocation, History } from 'history' import { ReactWrapper } from 'enzyme' import { IssueCollectorForm } from './IssueCollectorForm' -import { createTestComponent, mockDeclarationData } from '@client/tests/util' +import { + createTestComponent, + mockDeclarationData, + TestComponentWithRouteMock +} from '@client/tests/util' import { EventType } from '@client/utils/gateway' import { IssueCollectorFormForOthers } from './IssueFormForOthers' +import { formatUrl } from '@client/navigation' +import { ISSUE_COLLECTOR } from '@client/navigation/routes' let store: AppStore -let history: History -let location = createLocation('/') const declarationsHistory = [ { @@ -179,35 +182,32 @@ const birthDeclarationForIssuance = { beforeEach(() => { const s = createStore() store = s.store - history = s.history - location = createLocation('/') - history.location = location }) describe('Certificate issue collector test for a birth registration without father details', () => { describe('Test collector group', () => { let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , + { + store, + path: ISSUE_COLLECTOR, + initialEntries: [ + formatUrl(ISSUE_COLLECTOR, { registrationId: '6a5fd35d-01ec-4c37-976e-e055107a74a1', eventType: 'birth', groupId: 'collector' - }, - isExact: true, - path: '', - url: '' - }} - />, - { history, store } + }) + ] + } ) + component = testComponent }) @@ -242,31 +242,31 @@ describe('Certificate issue collector test for a birth registration without fath } } - const testComponent = await createTestComponent( - , - { history, store } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: ISSUE_COLLECTOR, + initialEntries: [ + formatUrl(ISSUE_COLLECTOR, { + registrationId: '6a5fd35d-01ec-4c37-976e-e055107a74a1', + groupId: 'collector' + }) + ] + } + ) component = testComponent + router = testRouter }) it('redirects to id check component upon FATHER option selection', async () => { component.find('#continue-button').hostNodes().simulate('click') component.update() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/issue/check/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth/father' ) }) @@ -291,23 +291,21 @@ describe('Certificate issue collector test for a birth registration without fath } } - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( , + { + store, + path: ISSUE_COLLECTOR, + initialEntries: [ + formatUrl(ISSUE_COLLECTOR, { registrationId: '6a5fd35d-01ec-4c37-976e-e055107a74a1', groupId: 'collector' - }, - isExact: true, - path: '', - url: '' - }} - />, - { history, store } + }) + ] + } ) component = testComponent @@ -319,7 +317,7 @@ describe('Certificate issue collector test for a birth registration without fath component.update() component.find('#continue-button').hostNodes().simulate('click') component.update() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/issue/6a5fd35d-01ec-4c37-976e-e055107a74a1/otherCollector' ) }) @@ -348,23 +346,21 @@ describe('Certificate issue collector test for a birth registration without fath } } - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , + { + store, + path: ISSUE_COLLECTOR, + initialEntries: [ + formatUrl(ISSUE_COLLECTOR, { registrationId: '6a5fd35d-01ec-4c37-976e-e055107a74a1', groupId: 'otherCollector' - }, - isExact: true, - path: '', - url: '' - }} - />, - { history, store } + }) + ] + } ) component = testComponent }) @@ -405,28 +401,26 @@ describe('Certificate issue collector test for a birth registration without fath } } - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( , + { + store, + path: ISSUE_COLLECTOR, + initialEntries: [ + formatUrl(ISSUE_COLLECTOR, { registrationId: '6a5fd35d-01ec-4c37-976e-e055107a74a1', groupId: 'otherCollector' - }, - isExact: true, - path: '', - url: '' - }} - />, - { history, store } + }) + ] + } ) component = testComponent component.find('#continue-button').hostNodes().simulate('click') component.update() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/issue/payment/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth' ) }) diff --git a/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssuePayment.test.tsx b/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssuePayment.test.tsx index 568e36c96a2..b28b5c2ebff 100644 --- a/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssuePayment.test.tsx +++ b/packages/client/src/views/IssueCertificate/IssueCollectorForm/IssuePayment.test.tsx @@ -10,7 +10,10 @@ */ import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { formatUrl } from '@client/navigation' -import { REGISTRAR_HOME_TAB } from '@client/navigation/routes' +import { + ISSUE_CERTIFICATE_PAYMENT, + REGISTRAR_HOME_TAB +} from '@client/navigation/routes' import { queries } from '@client/profile/queries' import { createStore } from '@client/store' import { @@ -22,10 +25,9 @@ import { } from '@client/tests/util' import { EventType } from '@client/utils/gateway' import * as React from 'react' -import { Mock, vi } from 'vitest' +import { Mock } from 'vitest' import { IssuePayment } from './IssuePayment' import { storeDeclaration } from '@client/declarations' -import { useParams } from 'react-router-dom' const getItem = window.localStorage.getItem as Mock ;(queries.fetchUserDetails as Mock).mockReturnValue(mockUserResponse) @@ -71,49 +73,48 @@ const deathDeclaration = { } describe('verify collector tests for issuance', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(validToken) - ;(useParams as Mock).mockImplementation(() => ({ - registrationId: 'mockBirth1234', - eventType: 'birth' - })) + // @ts-ignore store.dispatch(storeDeclaration(birthDeclaration)) }) it('when mother is collector renders issue payment component', async () => { - const testComponent = await createTestComponent(, { - store, - history - }) + const { component: testComponent } = await createTestComponent( + , + { + path: ISSUE_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(ISSUE_CERTIFICATE_PAYMENT, { + registrationId: 'mockBirth1234', + eventType: 'birth' + }) + ], + store + } + ) expect(testComponent.find('#service').hostNodes().text()).toContain('Birth') expect(testComponent.find('#amountDue').hostNodes().text()).toContain('20') testComponent.find('#Continue').hostNodes().simulate('click') }) it('invalid declaration id for issue certificate', async () => { - const { store, history } = createStore() - const mockLocation: any = vi.fn() - await createTestComponent( - , - { store, history } - ) + const { store } = createStore() - expect(history.location.pathname).toEqual( + const { router } = await createTestComponent(, { + store, + path: ISSUE_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(ISSUE_CERTIFICATE_PAYMENT, { + registrationId: 'mockBirth', + eventType: EventType.Birth + }) + ] + }) + + expect(router.state.location.pathname).toEqual( formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.readyToIssue, selectorId: '' @@ -123,22 +124,28 @@ describe('verify collector tests for issuance', () => { }) describe('in case of death declaration renders issue payment component', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(validToken) - ;(useParams as Mock).mockImplementation(() => ({ - registrationId: 'mockDeath1234', - eventType: 'death' - })) + //@ts-ignore store.dispatch(storeDeclaration(deathDeclaration)) }) it('when informant is collector', async () => { - const testComponent = await createTestComponent(, { - store, - history - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + path: ISSUE_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(ISSUE_CERTIFICATE_PAYMENT, { + registrationId: 'mockDeath1234', + eventType: 'death' + }) + ] + } + ) expect(testComponent.find('#service').hostNodes().text()).toContain('Death') expect(testComponent.find('#amountDue').hostNodes().text()).toContain('0.0') testComponent.find('#Continue').hostNodes().simulate('click') diff --git a/packages/client/src/views/OfficeHome/LoadingIndicator.test.tsx b/packages/client/src/views/OfficeHome/LoadingIndicator.test.tsx index c8532d7227e..96765448495 100644 --- a/packages/client/src/views/OfficeHome/LoadingIndicator.test.tsx +++ b/packages/client/src/views/OfficeHome/LoadingIndicator.test.tsx @@ -14,17 +14,17 @@ import { createTestComponent } from '@client/tests/util' import { createStore } from '@client/store' describe('LoadingIndicator test cases', () => { - const { store, history } = createStore() + const { store } = createStore() it('Should display the Error', async () => { // @ts-ignore - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) const isShowingLoadingText = testComponent.find( 'div#search-result-error-text-count' diff --git a/packages/client/src/views/OfficeHome/OfficeHome.test.tsx b/packages/client/src/views/OfficeHome/OfficeHome.test.tsx index 23a72d9efc1..42a1c9c189a 100644 --- a/packages/client/src/views/OfficeHome/OfficeHome.test.tsx +++ b/packages/client/src/views/OfficeHome/OfficeHome.test.tsx @@ -27,6 +27,8 @@ import { waitFor, waitForElement } from '@client/tests/wait-for-element' import { SELECTOR_ID } from './inProgress/InProgress' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { vi, Mock } from 'vitest' +import { REGISTRAR_HOME_TAB } from '@client/navigation/routes' +import { formatUrl } from '@client/navigation' const registerScopeToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsImNlcnRpZnkiLCJkZW1vIl0sImlhdCI6MTU0MjY4ODc3MCwiZXhwIjoxNTQzMjkzNTcwLCJhdWQiOlsib3BlbmNydnM6YXV0aC11c2VyIiwib3BlbmNydnM6dXNlci1tZ250LXVzZXIiLCJvcGVuY3J2czpoZWFydGgtdXNlciIsIm9wZW5jcnZzOmdhdGV3YXktdXNlciIsIm9wZW5jcnZzOm5vdGlmaWNhdGlvbi11c2VyIiwib3BlbmNydnM6d29ya2Zsb3ctdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1YmVhYWY2MDg0ZmRjNDc5MTA3ZjI5OGMifQ.ElQd99Lu7WFX3L_0RecU_Q7-WZClztdNpepo7deNHqzro-Cog4WLN7RW3ZS5PuQtMaiOq1tCb-Fm3h7t4l4KDJgvC11OyT7jD6R2s2OleoRVm3Mcw5LPYuUVHt64lR_moex0x_bCqS72iZmjrjS-fNlnWK5zHfYAjF2PWKceMTGk6wnI9N49f6VwwkinJcwJi6ylsjVkylNbutQZO0qTc7HRP-cBfAzNcKD37FqTRNpVSvHdzQSNcs7oiv3kInDN5aNa2536XSd3H-RiKR9hm9eID9bSIJgFIGzkWRd5jnoYxT70G0t03_mTVnDnqPXDtyI-lmerx24Ost0rQLUNIg' @@ -65,10 +67,10 @@ queries.fetchUserDetails = mockFetchUserDetails storage.getItem = vi.fn() storage.setItem = vi.fn() -let { store, history } = createStore() +let { store } = createStore() let client = createClient(store) beforeEach(async () => { - ;({ store, history } = createStore()) + ;({ store } = createStore()) client = createClient(store) getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) @@ -76,25 +78,16 @@ beforeEach(async () => { describe('OfficeHome related tests', () => { it('sets loading state while waiting for data', async () => { - const testComponent = await createTestComponent( - , - { store, history } + const { component: testComponent } = await createTestComponent( + , + { store } ) - // @ts-ignore - expect(testComponent.containsMatchingElement(Spinner)).toBe(true) + expect( + testComponent.containsMatchingElement( + Spinner as unknown as React.ReactElement + ) + ).toBe(true) }) describe('should load data', () => { @@ -113,19 +106,12 @@ describe('OfficeHome related tests', () => { client.query = mockListSyncController }) it('renders page with five tabs', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) await waitForElement(testComponent, '#navigation_progress') @@ -136,19 +122,12 @@ describe('OfficeHome related tests', () => { }) it('renders tabs with count', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) await flushPromises() @@ -191,184 +170,85 @@ describe('OfficeHome related tests', () => { client.query = mockListSyncController }) it('shows no-record message in inProgress drafts tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) await waitForElement(testComponent, '#no-record') }) it('shows no-record message in inProgress fieldagent drafts tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) await waitForElement(testComponent, '#no-record') }) it('shows no-record message in inProgress hospital drafts tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) await waitForElement(testComponent, '#no-record') }) - it('shows no-record message in review tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows no-record message in review tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() await waitForElement(testComponent, '#no-record') }) - it('shows no-record message in reject tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows no-record message in reject tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() await waitForElement(testComponent, '#no-record') }) - it('shows no-record message in approval tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows no-record message in approval tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() await waitForElement(testComponent, '#no-record') }) - it('shows no-record message in print tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows no-record message in print tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() await waitForElement(testComponent, '#no-record') }) - it('shows no-record message in externalValidation tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows no-record message in externalValidation tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() await waitForElement(testComponent, '#no-record') }) }) @@ -381,161 +261,124 @@ describe('OfficeHome related tests', () => { client.query = mockListSyncController }) it('shows error message in inProgress fieldagent drafts tab', async () => { - const testComponent = await createTestComponent( - , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.inProgress, selectorId: SELECTOR_ID.fieldAgentDrafts - }, - isExact: true, - path: '', - url: '' - }} - staticContext={undefined} - history={history} - location={history.location} - />, - { store, history, apolloClient: client } + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) + await waitForElement(testComponent, '#search-result-error-text-count') }) it('shows error message in inProgress hospital drafts tab', async () => { - const testComponent = await createTestComponent( - , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.inProgress, selectorId: SELECTOR_ID.hospitalDrafts - }, - isExact: true, - path: '', - url: '' - }} - staticContext={undefined} - history={history} - location={history.location} - />, - { store, history, apolloClient: client } + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) + await waitForElement(testComponent, '#search-result-error-text-count') }) - it('shows error message in review tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows error message in review tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { + tabId: WORKQUEUE_TABS.readyForReview + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() + await waitForElement(testComponent, '#search-result-error-text-count') }) - it('shows error message in reject tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows error message in reject tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { + tabId: WORKQUEUE_TABS.requiresUpdate + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() + await waitForElement(testComponent, '#search-result-error-text-count') }) - it('shows error message in approval tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows error message in approval tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { + tabId: WORKQUEUE_TABS.sentForApproval + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() + await waitForElement(testComponent, '#search-result-error-text-count') }) - it('shows error message in print tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows error message in print tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { + tabId: WORKQUEUE_TABS.readyToPrint + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() + await waitForElement(testComponent, '#search-result-error-text-count') }) - it('shows error message in externalValidation tab', async () => { - const testComponent = await createTestComponent( - , - { store, history, apolloClient: client } + it('shows error message in externalValidation tab', async () => { + const { component: testComponent } = await createTestComponent( + , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB, { + tabId: WORKQUEUE_TABS.externalValidation + }) + ] + } ) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - testComponent.update() + await waitForElement(testComponent, '#search-result-error-text-count') }) }) diff --git a/packages/client/src/views/OfficeHome/OfficeHome.tsx b/packages/client/src/views/OfficeHome/OfficeHome.tsx index ce27ad49620..99419c47cb8 100644 --- a/packages/client/src/views/OfficeHome/OfficeHome.tsx +++ b/packages/client/src/views/OfficeHome/OfficeHome.tsx @@ -54,7 +54,10 @@ import { getOfflineData } from '@client/offline/selectors' import { IOfflineData } from '@client/offline/reducer' import { EventType } from '@client/utils/gateway' import { SELECT_VITAL_EVENT } from '@client/navigation/routes' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' const FABContainer = styled.div` position: fixed; @@ -489,6 +492,7 @@ function mapStateToProps(state: IStoreState, props: RouteComponentProps) { (match.params.pageId && Number.parseInt(match.params.pageId)) || (match.params.selectorId && Number.parseInt(match.params.selectorId)) || 1 + return { offlineResources: getOfflineData(state), declarations: state.declarationsState.declarations, diff --git a/packages/client/src/views/OfficeHome/inExternalValidation/inExternalValidationTab.test.tsx b/packages/client/src/views/OfficeHome/inExternalValidation/inExternalValidationTab.test.tsx index 91a38e172cb..416b22504bf 100644 --- a/packages/client/src/views/OfficeHome/inExternalValidation/inExternalValidationTab.test.tsx +++ b/packages/client/src/views/OfficeHome/inExternalValidation/inExternalValidationTab.test.tsx @@ -14,7 +14,8 @@ import { ReactWrapper } from 'enzyme' import { createTestComponent, createTestStore, - resizeWindow + resizeWindow, + TestComponentWithRouteMock } from '@client/tests/util' import { InExternalValidationTab } from './InExternalValidationTab' import * as jwt from 'jsonwebtoken' @@ -23,7 +24,6 @@ import { checkAuth } from '@client/profile/profileActions' import type { GQLBirthEventSearchSet } from '@client/utils/gateway-deprecated-do-not-use' import { waitForElement } from '@client/tests/wait-for-element' import { Workqueue } from '@opencrvs/components/lib/Workqueue' -import { History } from 'history' import { vi, Mock } from 'vitest' import { EventType } from '@client/utils/gateway' @@ -72,24 +72,24 @@ const birthEventSearchSet: GQLBirthEventSearchSet = { describe('Registrar home external validation tab tests', () => { let component: ReactWrapper<{}, {}> - let history: History + let componentRouter: TestComponentWithRouteMock['router'] beforeEach(async () => { const SECONDARY_TIME = 1583322631424 // Wed Mar 04 2020 13:50:31 GMT+0200 (Eastern European Standard Time) Date.now = vi.fn(() => SECONDARY_TIME) - const { store: testStore, history: testHistory } = await createTestStore() + const { store: testStore } = await createTestStore() getItem.mockReturnValue(registerScopeToken) testStore.dispatch(checkAuth()) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( // @ts-ignore , - { store: testStore, history: testHistory } + { store: testStore } ) component = testComponent - history = testHistory + componentRouter = router }) it('renders data', async () => { @@ -109,7 +109,7 @@ describe('Registrar home external validation tab tests', () => { const dataRow = tableElement.find('#name_0').hostNodes() dataRow.simulate('click') component.update() - expect(history.location.pathname).toContain('record-audit') + expect(componentRouter.state.location.pathname).toContain('record-audit') }) describe('On devices with small viewport', () => { @@ -123,7 +123,7 @@ describe('Registrar home external validation tab tests', () => { const dataRow = tableElement.find('#name_0').hostNodes() dataRow.simulate('click') component.update() - expect(history.location.pathname).toContain('record-audit') + expect(componentRouter.state.location.pathname).toContain('record-audit') }) }) }) diff --git a/packages/client/src/views/OfficeHome/inProgress/inProgress.test.tsx b/packages/client/src/views/OfficeHome/inProgress/inProgress.test.tsx index b8e821b93f6..2cdab6581ca 100644 --- a/packages/client/src/views/OfficeHome/inProgress/inProgress.test.tsx +++ b/packages/client/src/views/OfficeHome/inProgress/inProgress.test.tsx @@ -75,7 +75,7 @@ queries.fetchUserDetails = mockFetchUserDetails storage.getItem = vi.fn() storage.setItem = vi.fn() -const { store, history } = createStore() +const { store } = createStore() beforeAll(() => { getItem.mockReturnValue(registerScopeToken) store.dispatch(checkAuth()) @@ -95,7 +95,7 @@ describe('In Progress tab', () => { data: {} } ] - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -129,7 +129,7 @@ describe('In Progress tab', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.inProgress, selectorId: SELECTOR_ID.ownDrafts @@ -142,7 +142,7 @@ describe('In Progress tab', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.inProgress, selectorId: SELECTOR_ID.fieldAgentDrafts @@ -164,7 +164,7 @@ describe('In Progress tab', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -266,7 +266,7 @@ describe('In Progress tab', () => { } ] // @ts-ignore - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -309,7 +309,7 @@ describe('In Progress tab', () => { for (let i = 0; i < 12; i++) { drafts.push(createDeclaration(EventType.Birth)) } - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -416,7 +416,7 @@ describe('In Progress tab', () => { ] // @ts-ignore store.dispatch(storeDeclaration(drafts)) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -453,7 +453,7 @@ describe('In Progress tab', () => { setTimeout(resolve, 100) }) testComponent.update() - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( '/drafts/cc66d69c-7f0a-4047-9283-f066571830f4' ) }) @@ -464,7 +464,7 @@ describe('In Progress tab', () => { const TIME_STAMP = '1562912635549' const drafts: IDeclaration[] = [] drafts.push(createDeclaration(EventType.Birth)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -557,7 +557,7 @@ describe('In Progress tab', () => { vi.clearAllMocks() const drafts: IDeclaration[] = [] drafts.push(createDeclaration(EventType.Birth)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -599,7 +599,7 @@ describe('In Progress tab', () => { const drafts: IDeclaration[] = [] drafts.push(createDeclaration(EventType.Birth)) // @ts-ignore - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -688,7 +688,7 @@ describe('In Progress tab', () => { await flushPromises() testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/notificationTab/956281c9-1f47-4c26-948a-970dd23c4094' ) }) @@ -740,9 +740,9 @@ describe('In Progress tab', () => { ) downloadableDeclaration.downloadStatus = undefined store.dispatch(modifyDeclaration(downloadableDeclaration)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) expect( @@ -757,9 +757,9 @@ describe('In Progress tab', () => { ) downloadableDeclaration.downloadStatus = DOWNLOAD_STATUS.DOWNLOADING store.dispatch(modifyDeclaration(downloadableDeclaration)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) expect( @@ -774,9 +774,9 @@ describe('In Progress tab', () => { ) downloadableDeclaration.downloadStatus = DOWNLOAD_STATUS.DOWNLOADED store.dispatch(modifyDeclaration(downloadableDeclaration)) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( , - { store, history } + { store } ) expect( @@ -793,7 +793,7 @@ describe('In Progress tab', () => { }) testComponent.update() - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId, pageId: 'review', @@ -809,9 +809,9 @@ describe('In Progress tab', () => { ) downloadableDeclaration.downloadStatus = DOWNLOAD_STATUS.FAILED store.dispatch(modifyDeclaration(downloadableDeclaration)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) expect( testComponent.find('#ListItemAction-0-icon-failed').hostNodes() @@ -826,7 +826,7 @@ describe('In Progress tab', () => { const birthNotificationSentDateStr = '2019-10-20T11:03:20.660Z' const drafts: IDeclaration[] = [] drafts.push(createDeclaration(EventType.Birth)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -941,7 +941,7 @@ describe('In Progress tab', () => { const declarationId = 'e302f7c5-ad87-4117-91c1-35eaf2ea7be8' // @ts-ignore - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { pageSize={10} onPageChange={(pageId: number) => {}} />, - { store, history } + { store } ) getItem.mockReturnValue(registerScopeToken) @@ -995,7 +995,7 @@ describe('In Progress tab', () => { }) testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/inProgressTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) }) diff --git a/packages/client/src/views/OfficeHome/outbox/Outbox.test.tsx b/packages/client/src/views/OfficeHome/outbox/Outbox.test.tsx index f427e8bf606..d66621e3ccf 100644 --- a/packages/client/src/views/OfficeHome/outbox/Outbox.test.tsx +++ b/packages/client/src/views/OfficeHome/outbox/Outbox.test.tsx @@ -43,12 +43,16 @@ describe('outbox component tests', () => { React.Component<{}, {}, any> > let store: AppStore - let history + beforeAll(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history - testComponent = await createTestComponent(, { store, history }) + + const { component } = await createTestComponent(, { + store + }) + + testComponent = component }) describe('when there is no data', () => { diff --git a/packages/client/src/views/OfficeHome/readyForReview/readyForReview.test.tsx b/packages/client/src/views/OfficeHome/readyForReview/readyForReview.test.tsx index 9af994a24f9..e5609ad317d 100644 --- a/packages/client/src/views/OfficeHome/readyForReview/readyForReview.test.tsx +++ b/packages/client/src/views/OfficeHome/readyForReview/readyForReview.test.tsx @@ -20,10 +20,10 @@ import { checkAuth } from '@client/profile/profileActions' import { queries } from '@client/profile/queries' import { createStore } from '@client/store' import { - createRouterProps, createTestComponent, mockUserResponse, - resizeWindow + resizeWindow, + TestComponentWithRouteMock } from '@client/tests/util' import { waitForElement, waitFor } from '@client/tests/wait-for-element' import { createClient } from '@client/utils/apolloClient' @@ -32,7 +32,6 @@ import { OfficeHome } from '@client/views/OfficeHome/OfficeHome' import { EVENT_STATUS } from '@client/workqueue' import { Workqueue } from '@opencrvs/components/lib/Workqueue' import { ApolloClient } from '@apollo/client' -import { ReactWrapper } from 'enzyme' import { merge } from 'lodash' import * as React from 'react' import { ReadyForReview } from './ReadyForReview' @@ -41,9 +40,6 @@ import type { GQLDeathEventSearchSet } from '@client/utils/gateway-deprecated-do-not-use' import { formattedDuration } from '@client/utils/date-formatting' -import { REGISTRAR_HOME } from '@client/navigation/routes' -import { formatUrl } from '@client/navigation' -import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { birthDeclarationForReview } from '@client/tests/mock-graphql-responses' import { vi, Mock } from 'vitest' @@ -232,14 +228,12 @@ const mockReviewTabData = { describe('OfficeHome sent for review tab related tests', () => { let store: ReturnType['store'] - let history: ReturnType['history'] let apolloClient: ApolloClient<{}> beforeEach(async () => { ;(queries.fetchUserDetails as Mock).mockReturnValue(mockUserResponse) const createdStore = createStore() store = createdStore.store - history = createdStore.history apolloClient = createClient(store) @@ -250,7 +244,7 @@ describe('OfficeHome sent for review tab related tests', () => { it('should show pagination bar if items more than 11 in ReviewTab', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const pagination = await waitForElement( @@ -285,7 +279,7 @@ describe('OfficeHome sent for review tab related tests', () => { it('renders all items returned from graphql query in ready for review', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const workqueue = await waitForElement(testComponent, Workqueue) @@ -319,7 +313,7 @@ describe('OfficeHome sent for review tab related tests', () => { it('returns an empty array incase of invalid graphql query response', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const workqueue = await waitForElement(testComponent, Workqueue) @@ -344,7 +338,7 @@ describe('OfficeHome sent for review tab related tests', () => { it('redirects to recordAudit page if row is clicked', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const element = await waitForElement(testComponent, '#name_0') element.hostNodes().simulate('click') await waitFor(() => - window.location.href.includes( + router.state.location.pathname.includes( '/record-audit/reviewTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) ) }) describe('handles download status', () => { - let testComponent: ReactWrapper<{}, {}> - let createdTestComponent: ReactWrapper<{}, {}> + let testComponent: TestComponentWithRouteMock + let createdTestComponent: TestComponentWithRouteMock beforeEach(async () => { Date.now = vi.fn(() => 1554055200000) @@ -474,45 +468,40 @@ describe('OfficeHome sent for review tab related tests', () => { }) apolloClient.query = mockListSyncController - createdTestComponent = await createTestComponent( - , - { store, history, apolloClient } - ) + createdTestComponent = await createTestComponent(, { + store, + apolloClient + }) testComponent = createdTestComponent }) //TODO:: FAILED TEST it.skip('downloads declaration after clicking download button', async () => { - await waitForElement(testComponent, '#ListItemAction-0-icon') - testComponent.find('#ListItemAction-0-icon').hostNodes().simulate('click') - testComponent.update() - expect(testComponent.find('#assignment').hostNodes()).toHaveLength(1) + await waitForElement(testComponent.component, '#ListItemAction-0-icon') + testComponent.component + .find('#ListItemAction-0-icon') + .hostNodes() + .simulate('click') + testComponent.component.update() + expect( + testComponent.component.find('#assignment').hostNodes() + ).toHaveLength(1) - testComponent.find('#assign').hostNodes().simulate('click') + testComponent.component.find('#assign').hostNodes().simulate('click') expect( - testComponent.find('#action-loading-ListItemAction-0').hostNodes() + testComponent.component + .find('#action-loading-ListItemAction-0') + .hostNodes() ).toHaveLength(1) await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() + testComponent.component.update() const action = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-0-Review' ) action.hostNodes().simulate('click') @@ -520,8 +509,8 @@ describe('OfficeHome sent for review tab related tests', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() - expect(history.location.pathname).toBe( + testComponent.component.update() + expect(testComponent.router.state.location.pathname).toBe( '/reviews/9a55d213-ad9f-4dcd-9418-340f3a7f6269/events/birth/parent/review' ) }) @@ -535,10 +524,12 @@ describe('OfficeHome sent for review tab related tests', () => { downloadedDeclaration.downloadStatus = DOWNLOAD_STATUS.FAILED store.dispatch(storeDeclaration(downloadedDeclaration)) - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#ListItemAction-1-icon-failed').hostNodes() + testComponent.component + .find('#ListItemAction-1-icon-failed') + .hostNodes() ).toHaveLength(1) }) }) @@ -547,7 +538,7 @@ describe('OfficeHome sent for review tab related tests', () => { const TIME_STAMP = '1544188309380' Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const props = testComponent.find('#declaration_icon').first().props().color @@ -620,8 +611,8 @@ describe('OfficeHome sent for review tab related tests', () => { }) describe.skip('handles download status for possible duplicate declaration', () => { - let testComponent: ReactWrapper<{}, {}> - let createdTestComponent: ReactWrapper<{}, {}> + let testComponent: TestComponentWithRouteMock + let createdTestComponent: TestComponentWithRouteMock beforeAll(async () => { Date.now = vi.fn(() => 1554055200000) const graphqlMocks = [ @@ -657,7 +648,7 @@ describe('OfficeHome sent for review tab related tests', () => { createdTestComponent = await createTestComponent( // @ts-ignore , - { store, history, graphqlMocks } + { store, graphqlMocks } ) getItem.mockReturnValue(registerScopeToken) @@ -667,15 +658,17 @@ describe('OfficeHome sent for review tab related tests', () => { it('starts downloading after clicking download button', async () => { const downloadButton = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-1-icon' ) downloadButton.hostNodes().simulate('click') - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#action-loading-ListItemAction-1').hostNodes() + testComponent.component + .find('#action-loading-ListItemAction-1') + .hostNodes() ).toHaveLength(1) }) @@ -689,7 +682,7 @@ describe('OfficeHome sent for review tab related tests', () => { store.dispatch(modifyDeclaration(downloadedDeclaration)) const action = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-1-Review' ) @@ -697,7 +690,7 @@ describe('OfficeHome sent for review tab related tests', () => { action.hostNodes().simulate('click') await waitFor(() => - window.location.href.includes( + testComponent.router.state.location.pathname.includes( '/duplicates/bc09200d-0160-43b4-9e2b-5b9e90424e95' ) ) @@ -712,10 +705,10 @@ describe('OfficeHome sent for review tab related tests', () => { downloadedDeclaration.downloadStatus = DOWNLOAD_STATUS.FAILED store.dispatch(modifyDeclaration(downloadedDeclaration)) - testComponent.update() + testComponent.component.update() const errorIcon = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-1-download-failed' ) @@ -725,12 +718,12 @@ describe('OfficeHome sent for review tab related tests', () => { }) describe('Tablet tests', () => { - let { store, history } = createStore() + let { store } = createStore() beforeAll(async () => { const s = createStore() store = s.store - history = s.history + resizeWindow(800, 1280) }) @@ -742,7 +735,7 @@ describe('Tablet tests', () => { const TIME_STAMP = '1544188309380' Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) getItem.mockReturnValue(registerScopeToken) @@ -822,7 +815,7 @@ describe('Tablet tests', () => { const row = await waitForElement(testComponent, '#name_0') row.hostNodes().simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/reviewTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) }) diff --git a/packages/client/src/views/OfficeHome/readyToPrint/readyToPrint.test.tsx b/packages/client/src/views/OfficeHome/readyToPrint/readyToPrint.test.tsx index b349d8aaded..2229cc78e31 100644 --- a/packages/client/src/views/OfficeHome/readyToPrint/readyToPrint.test.tsx +++ b/packages/client/src/views/OfficeHome/readyToPrint/readyToPrint.test.tsx @@ -22,13 +22,13 @@ import { createStore } from '@client/store' import { createTestComponent, mockUserResponse, - resizeWindow + resizeWindow, + TestComponentWithRouteMock } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' import { createClient } from '@client/utils/apolloClient' import { OfficeHome } from '@client/views/OfficeHome/OfficeHome' import { Workqueue } from '@opencrvs/components/lib/Workqueue' -import { ReactWrapper } from 'enzyme' import { merge } from 'lodash' import * as React from 'react' import { ReadyToPrint } from './ReadyToPrint' @@ -38,6 +38,8 @@ import type { } from '@client/utils/gateway-deprecated-do-not-use' import { formattedDuration } from '@client/utils/date-formatting' import { vi, Mock } from 'vitest' +import { formatUrl } from '@client/navigation' +import { REGISTRAR_HOME_TAB } from '@client/navigation/routes' const registerScopeToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsImNlcnRpZnkiLCJkZW1vIl0sImlhdCI6MTU0MjY4ODc3MCwiZXhwIjoxNTQzMjkzNTcwLCJhdWQiOlsib3BlbmNydnM6YXV0aC11c2VyIiwib3BlbmNydnM6dXNlci1tZ250LXVzZXIiLCJvcGVuY3J2czpoZWFydGgtdXNlciIsIm9wZW5jcnZzOmdhdGV3YXktdXNlciIsIm9wZW5jcnZzOm5vdGlmaWNhdGlvbi11c2VyIiwib3BlbmNydnM6d29ya2Zsb3ctdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1YmVhYWY2MDg0ZmRjNDc5MTA3ZjI5OGMifQ.ElQd99Lu7WFX3L_0RecU_Q7-WZClztdNpepo7deNHqzro-Cog4WLN7RW3ZS5PuQtMaiOq1tCb-Fm3h7t4l4KDJgvC11OyT7jD6R2s2OleoRVm3Mcw5LPYuUVHt64lR_moex0x_bCqS72iZmjrjS-fNlnWK5zHfYAjF2PWKceMTGk6wnI9N49f6VwwkinJcwJi6ylsjVkylNbutQZO0qTc7HRP-cBfAzNcKD37FqTRNpVSvHdzQSNcs7oiv3kInDN5aNa2536XSd3H-RiKR9hm9eID9bSIJgFIGzkWRd5jnoYxT70G0t03_mTVnDnqPXDtyI-lmerx24Ost0rQLUNIg' @@ -237,7 +239,7 @@ storage.getItem = vi.fn() storage.setItem = vi.fn() describe('RegistrarHome ready to print tab related tests', () => { - const { store, history } = createStore() + const { store } = createStore() const client = createClient(store) beforeAll(async () => { @@ -329,7 +331,7 @@ describe('RegistrarHome ready to print tab related tests', () => { ] } - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { } }} />, - { store, history } + { store } ) const element = await waitForElement(testComponent, Workqueue) @@ -359,14 +361,14 @@ describe('RegistrarHome ready to print tab related tests', () => { it('returns an empty array incase of invalid graphql query response', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) testComponent.update() @@ -377,7 +379,7 @@ describe('RegistrarHome ready to print tab related tests', () => { it('should show pagination bar if items are more than 11 in ready for print tab', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const element = await waitForElement(testComponent, '#pagination_container') @@ -406,14 +408,14 @@ describe('RegistrarHome ready to print tab related tests', () => { describe('When a row is clicked', () => { it('renders expanded area for ready to print', async () => { - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) // wait for mocked data to load mockedProvider @@ -426,15 +428,15 @@ describe('RegistrarHome ready to print tab related tests', () => { await waitForElement(testComponent, '#name_0') testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/printTab/956281c9-1f47-4c26-948a-970dd23c4094' ) }) }) describe('handles download status', () => { - let testComponent: ReactWrapper<{}, {}> - let createdTestComponent: ReactWrapper<{}, {}> + let testComponent: TestComponentWithRouteMock + beforeEach(async () => { Date.now = vi.fn(() => 1554055200000) mockListSyncController @@ -704,38 +706,43 @@ describe('RegistrarHome ready to print tab related tests', () => { }) client.query = mockListSyncController - createdTestComponent = await createTestComponent( - // @ts-ignore - , - { store, history, apolloClient: client } - ) - testComponent = createdTestComponent + testComponent = await createTestComponent(, { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB, + initialEntries: [formatUrl(REGISTRAR_HOME_TAB, { tabId: 'print' })] + }) }) it('downloads declaration after clicking download button', async () => { + testComponent.component.update() const downloadButton = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-0-icon' ) downloadButton.hostNodes().simulate('click') - testComponent.update() + testComponent.component.update() - expect(testComponent.find('#assignment').hostNodes()).toHaveLength(1) + expect( + testComponent.component.find('#assignment').hostNodes() + ).toHaveLength(1) - testComponent.find('#assign').hostNodes().simulate('click') + testComponent.component.find('#assign').hostNodes().simulate('click') expect( - testComponent.find('#action-loading-ListItemAction-0').hostNodes() + testComponent.component + .find('#action-loading-ListItemAction-0') + .hostNodes() ).toHaveLength(1) await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() + testComponent.component.update() const action = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-0-Print' ) action.hostNodes().simulate('click') @@ -743,8 +750,8 @@ describe('RegistrarHome ready to print tab related tests', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() - expect(history.location.pathname).toBe( + testComponent.component.update() + expect(testComponent.router.state.location.pathname).toBe( '/cert/collector/956281c9-1f47-4c26-948a-970dd23c4094/death/certCollector' ) }) @@ -758,10 +765,10 @@ describe('RegistrarHome ready to print tab related tests', () => { downloadedDeclaration.downloadStatus = DOWNLOAD_STATUS.FAILED store.dispatch(storeDeclaration(downloadedDeclaration)) - testComponent.update() + testComponent.component.update() const errorIcon = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-1-icon-failed' ) expect(errorIcon.hostNodes()).toHaveLength(1) @@ -770,7 +777,7 @@ describe('RegistrarHome ready to print tab related tests', () => { }) describe('Tablet tests', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(registerScopeToken) @@ -785,14 +792,14 @@ describe('Tablet tests', () => { it('redirects to recordAudit page if item is clicked', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) testComponent.update() @@ -804,7 +811,7 @@ describe('Tablet tests', () => { }) testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/printTab/956281c9-1f47-4c26-948a-970dd23c4094' ) }) diff --git a/packages/client/src/views/OfficeHome/requiresUpdate/requiresUpdate.test.tsx b/packages/client/src/views/OfficeHome/requiresUpdate/requiresUpdate.test.tsx index 43062e666b3..a50c419f603 100644 --- a/packages/client/src/views/OfficeHome/requiresUpdate/requiresUpdate.test.tsx +++ b/packages/client/src/views/OfficeHome/requiresUpdate/requiresUpdate.test.tsx @@ -23,13 +23,13 @@ import { createTestComponent, mockUserResponse, resizeWindow, - registrationClerkScopeToken + registrationClerkScopeToken, + TestComponentWithRouteMock } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' import { createClient } from '@client/utils/apolloClient' import { OfficeHome } from '@client/views/OfficeHome/OfficeHome' import { Workqueue } from '@opencrvs/components/lib/Workqueue' -import { ReactWrapper } from 'enzyme' import { merge } from 'lodash' import * as React from 'react' import { RequiresUpdate } from './RequiresUpdate' @@ -41,6 +41,8 @@ import { formattedDuration } from '@client/utils/date-formatting' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { birthDeclarationForReview } from '@client/tests/mock-graphql-responses' import { vi, Mock } from 'vitest' +import { formatUrl } from '@client/navigation' +import { REGISTRAR_HOME_TAB_PAGE } from '@client/navigation/routes' const registerScopeToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsImNlcnRpZnkiLCJkZW1vIl0sImlhdCI6MTU0MjY4ODc3MCwiZXhwIjoxNTQzMjkzNTcwLCJhdWQiOlsib3BlbmNydnM6YXV0aC11c2VyIiwib3BlbmNydnM6dXNlci1tZ250LXVzZXIiLCJvcGVuY3J2czpoZWFydGgtdXNlciIsIm9wZW5jcnZzOmdhdGV3YXktdXNlciIsIm9wZW5jcnZzOm5vdGlmaWNhdGlvbi11c2VyIiwib3BlbmNydnM6d29ya2Zsb3ctdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1YmVhYWY2MDg0ZmRjNDc5MTA3ZjI5OGMifQ.ElQd99Lu7WFX3L_0RecU_Q7-WZClztdNpepo7deNHqzro-Cog4WLN7RW3ZS5PuQtMaiOq1tCb-Fm3h7t4l4KDJgvC11OyT7jD6R2s2OleoRVm3Mcw5LPYuUVHt64lR_moex0x_bCqS72iZmjrjS-fNlnWK5zHfYAjF2PWKceMTGk6wnI9N49f6VwwkinJcwJi6ylsjVkylNbutQZO0qTc7HRP-cBfAzNcKD37FqTRNpVSvHdzQSNcs7oiv3kInDN5aNa2536XSd3H-RiKR9hm9eID9bSIJgFIGzkWRd5jnoYxT70G0t03_mTVnDnqPXDtyI-lmerx24Ost0rQLUNIg' @@ -159,7 +161,7 @@ storage.getItem = vi.fn() storage.setItem = vi.fn() describe('OfficeHome sent for update tab related tests', () => { - const { store, history } = createStore() + const { store } = createStore() const client = createClient(store) beforeAll(async () => { @@ -172,7 +174,7 @@ describe('OfficeHome sent for update tab related tests', () => { const birthEventRejectedDate = '2019-10-20T11:03:20.660Z' - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { } }} />, - { store, history } + { store } ) const table = await waitForElement(testComponent, Workqueue) @@ -301,7 +303,7 @@ describe('OfficeHome sent for update tab related tests', () => { it('returns an empty array incase of invalid graphql query response', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { } }} />, - { store, history } + { store } ) const table = await waitForElement(testComponent, Workqueue) @@ -321,8 +323,8 @@ describe('OfficeHome sent for update tab related tests', () => { }) describe('handles download status', () => { - let testComponent: ReactWrapper<{}, {}> - let createdTestComponent: ReactWrapper<{}, {}> + let testComponent: TestComponentWithRouteMock + let createdTestComponent: TestComponentWithRouteMock beforeEach(async () => { const TIME_STAMP = '1544188309380' Date.now = vi.fn(() => 1554055200000) @@ -414,17 +416,17 @@ describe('OfficeHome sent for update tab related tests', () => { createdTestComponent = await createTestComponent( // @ts-ignore - , + { + store, + apolloClient: client, + path: REGISTRAR_HOME_TAB_PAGE, + initialEntries: [ + formatUrl(REGISTRAR_HOME_TAB_PAGE, { tabId: WORKQUEUE_TABS.requiresUpdate - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history, apolloClient: client } + }) + ] + } ) testComponent = createdTestComponent getItem.mockReturnValue(registerScopeToken) @@ -433,28 +435,32 @@ describe('OfficeHome sent for update tab related tests', () => { it('downloads the declaration after clicking download button', async () => { const downloadButton = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-0-icon' ) downloadButton.hostNodes().simulate('click') - testComponent.update() + testComponent.component.update() - expect(testComponent.find('#assignment').hostNodes()).toHaveLength(1) - testComponent.find('#assign').hostNodes().simulate('click') + expect( + testComponent.component.find('#assignment').hostNodes() + ).toHaveLength(1) + testComponent.component.find('#assign').hostNodes().simulate('click') expect( - testComponent.find('#action-loading-ListItemAction-0').hostNodes() + testComponent.component + .find('#action-loading-ListItemAction-0') + .hostNodes() ).toHaveLength(1) await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() + testComponent.component.update() const action = await waitForElement( - testComponent, + testComponent.component, '#ListItemAction-0-Update' ) action.hostNodes().simulate('click') @@ -462,8 +468,8 @@ describe('OfficeHome sent for update tab related tests', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - testComponent.update() - expect(history.location.pathname).toBe( + testComponent.component.update() + expect(testComponent.router.state.location.pathname).toBe( '/reviews/9a55d213-ad9f-4dcd-9418-340f3a7f6269/events/birth/parent/review' ) }) @@ -476,16 +482,18 @@ describe('OfficeHome sent for update tab related tests', () => { ) downloadedDeclaration.downloadStatus = DOWNLOAD_STATUS.FAILED store.dispatch(storeDeclaration(downloadedDeclaration)) - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#ListItemAction-1-icon-failed').hostNodes() + testComponent.component + .find('#ListItemAction-1-icon-failed') + .hostNodes() ).toHaveLength(1) }) }) }) describe('Tablet tests', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(registerScopeToken) @@ -501,7 +509,7 @@ describe('Tablet tests', () => { const TIME_STAMP = '1544188309380' Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( // @ts-ignore { } }} />, - { store, history } + { store } ) const element = await waitForElement(testComponent, '#name_0') @@ -579,7 +587,7 @@ describe('Tablet tests', () => { }) testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/rejectTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) }) diff --git a/packages/client/src/views/OfficeHome/sentForReview/SentForReview.test.tsx b/packages/client/src/views/OfficeHome/sentForReview/SentForReview.test.tsx index 979336f15b9..be1b97d449f 100644 --- a/packages/client/src/views/OfficeHome/sentForReview/SentForReview.test.tsx +++ b/packages/client/src/views/OfficeHome/sentForReview/SentForReview.test.tsx @@ -27,7 +27,6 @@ import type { GQLDeathEventSearchSet } from '@client/utils/gateway-deprecated-do-not-use' import { formattedDuration } from '@client/utils/date-formatting' -import { History } from 'history' import { vi, Mock } from 'vitest' import { EventType } from '@client/utils/gateway' @@ -139,9 +138,9 @@ const getItem = window.localStorage.getItem as Mock describe('RegistrationHome sent for approval tab related tests', () => { let store: AppStore - let history: History + beforeEach(async () => { - ;({ store, history } = createStore()) + ;({ store } = createStore()) getItem.mockReturnValue(validateScopeToken) await store.dispatch(checkAuth()) }) @@ -151,7 +150,7 @@ describe('RegistrationHome sent for approval tab related tests', () => { Date.now = vi.fn(() => 1554055200000) const sentForApprovalDate = '2019-10-20T11:03:20.660Z' - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) testComponent.update() @@ -265,7 +264,7 @@ describe('RegistrationHome sent for approval tab related tests', () => { it('returns an empty array incase of invalid graphql query response', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) const data = (await waitForElement(testComponent, Workqueue)).prop( @@ -291,7 +290,7 @@ describe('RegistrationHome sent for approval tab related tests', () => { it('should show pagination if items more than 10 in Approval Tab', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) expect( @@ -322,7 +321,7 @@ describe('RegistrationHome sent for approval tab related tests', () => { it('should show pagination and page number as per need ', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) expect( @@ -348,7 +347,7 @@ describe('RegistrationHome sent for approval tab related tests', () => { it('redirect to recordAudit page if item is clicked on desktop view ', async () => { Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) testComponent.update() @@ -452,14 +451,14 @@ describe('RegistrationHome sent for approval tab related tests', () => { }) testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/approvalTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) }) }) describe('Tablet tests', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(validateScopeToken) @@ -476,7 +475,7 @@ describe('Tablet tests', () => { const TIME_STAMP = '1544188309380' Date.now = vi.fn(() => 1554055200000) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { loading={false} error={false} />, - { store, history } + { store } ) testComponent.update() @@ -559,7 +558,7 @@ describe('Tablet tests', () => { }) testComponent.update() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( '/record-audit/approvalTab/e302f7c5-ad87-4117-91c1-35eaf2ea7be8' ) }) diff --git a/packages/client/src/views/Organisation/AdministrativeLevels.tsx b/packages/client/src/views/Organisation/AdministrativeLevels.tsx index f65d15c5891..9e4dc938684 100644 --- a/packages/client/src/views/Organisation/AdministrativeLevels.tsx +++ b/packages/client/src/views/Organisation/AdministrativeLevels.tsx @@ -121,7 +121,7 @@ export function AdministrativeLevels() { } const dataLocations = useSelector( - getNewLevel(locationId) + getNewLevel(locationId!) ) const totalNumber = dataLocations.childLocations.length const [currentPageNumber, setCurrentPageNumber] = React.useState(1) diff --git a/packages/client/src/views/PIN/CreatePin.test.tsx b/packages/client/src/views/PIN/CreatePin.test.tsx index ae58be67432..3e2d630593e 100644 --- a/packages/client/src/views/PIN/CreatePin.test.tsx +++ b/packages/client/src/views/PIN/CreatePin.test.tsx @@ -37,10 +37,10 @@ describe('Create PIN view', () => { let c: ReactWrapper beforeEach(async () => { - const { store, history } = createStore() - const testComponent = await createTestComponent( + const { store } = createStore() + const { component: testComponent } = await createTestComponent( null} />, - { store, history } + { store } ) c = testComponent diff --git a/packages/client/src/views/Performance/Dashboard.test.tsx b/packages/client/src/views/Performance/Dashboard.test.tsx index ab1971d6e09..dd55e1268e5 100644 --- a/packages/client/src/views/Performance/Dashboard.test.tsx +++ b/packages/client/src/views/Performance/Dashboard.test.tsx @@ -9,18 +9,14 @@ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { - createRouterProps, - createTestComponent, - createTestStore -} from '@client/tests/util' -import { ReactWrapper } from 'enzyme' import { AppStore } from '@client/store' -import { vi } from 'vitest' -import React from 'react' +import { createTestComponent, createTestStore } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' -import { DashboardEmbedView } from './Dashboard' import { Activity } from '@opencrvs/components/lib/icons' +import { ReactWrapper } from 'enzyme' +import React from 'react' +import { vi } from 'vitest' +import { DashboardEmbedView } from './Dashboard' describe('Leaderboards component', () => { let component: ReactWrapper<{}, {}> @@ -31,17 +27,13 @@ describe('Leaderboards component', () => { ;({ store } = await createTestStore()) }) beforeEach(async () => { - const { history } = createRouterProps('/performance/dashboard', { - isNavigatedInsideApp: false - }) - - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( } />, { - history, store } ) + component = testComponent }) it('renders no content component without crashing', async () => { await waitForElement(component, '#dashboard_noContent') diff --git a/packages/client/src/views/Performance/FieldAgentList.test.tsx b/packages/client/src/views/Performance/FieldAgentList.test.tsx index aa822204c50..54e383ddf58 100644 --- a/packages/client/src/views/Performance/FieldAgentList.test.tsx +++ b/packages/client/src/views/Performance/FieldAgentList.test.tsx @@ -31,7 +31,7 @@ describe('Field agent list tests', () => { }) beforeEach(async () => { - const { history, location, match } = createRouterProps( + const { location } = createRouterProps( '/performance/field-agents', { isNavigatedInsideApp: false }, { @@ -94,9 +94,13 @@ describe('Field agent list tests', () => { } } ] - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMock } + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: graphqlMock, + initialEntries: [location.pathname + '?' + location.search] + } ) component = testComponent }) @@ -118,7 +122,7 @@ describe('Field agent list tests', () => { }) it('For graphql errors it renders with error components', async () => { - const { history, location, match } = createRouterProps( + const { location } = createRouterProps( '/performance/field-agents', { isNavigatedInsideApp: false }, { @@ -130,10 +134,14 @@ describe('Field agent list tests', () => { } } ) - const testErrorComponent = await createTestComponent( - , - { store, history } + + const testErrorComponent = await createTestComponent(, { + store, + initialEntries: [location.pathname + '?' + location.search] + }) + await waitForElement( + testErrorComponent.component, + '#field-agent-error-list' ) - await waitForElement(testErrorComponent, '#field-agent-error-list') }) }) diff --git a/packages/client/src/views/Performance/RegistrationsList.test.tsx b/packages/client/src/views/Performance/RegistrationsList.test.tsx index 22310cd2917..8e5e8afc9fc 100644 --- a/packages/client/src/views/Performance/RegistrationsList.test.tsx +++ b/packages/client/src/views/Performance/RegistrationsList.test.tsx @@ -31,7 +31,7 @@ describe('Registrations List test', () => { }) beforeEach(async () => { - const { history, location, match } = createRouterProps( + const { location } = createRouterProps( '/performance/registrations', { isNavigatedInsideApp: false }, { @@ -172,9 +172,13 @@ describe('Registrations List test', () => { } } ] - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMock } + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: graphqlMock, + initialEntries: [location.pathname + '?' + location.search] + } ) component = testComponent }) diff --git a/packages/client/src/views/PrintCertificate/Payment.test.tsx b/packages/client/src/views/PrintCertificate/Payment.test.tsx index 3b0e820d4a0..4d68db07bbb 100644 --- a/packages/client/src/views/PrintCertificate/Payment.test.tsx +++ b/packages/client/src/views/PrintCertificate/Payment.test.tsx @@ -23,17 +23,19 @@ import { EventType } from '@client/utils/gateway' import { Payment } from './Payment' import { queries } from '@client/profile/queries' import { checkAuth } from '@client/profile/profileActions' -import { vi, Mock } from 'vitest' +import { Mock } from 'vitest' import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' -import { REGISTRAR_HOME_TAB } from '@client/navigation/routes' +import { + PRINT_CERTIFICATE_PAYMENT, + REGISTRAR_HOME_TAB +} from '@client/navigation/routes' import { formatUrl } from '@client/navigation' const getItem = window.localStorage.getItem as Mock ;(queries.fetchUserDetails as Mock).mockReturnValue(mockUserResponse) describe('verify collector tests', () => { - const { store, history } = createStore() - const mockLocation: any = vi.fn() + const { store } = createStore() const birthDeclaration = { id: 'mockBirth1234', @@ -75,21 +77,18 @@ describe('verify collector tests', () => { }) it('when mother is collector renders Payment component', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: PRINT_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(PRINT_CERTIFICATE_PAYMENT, { registrationId: 'mockBirth1234', eventType: EventType.Birth - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#service').hostNodes().text()).toContain( @@ -109,7 +108,7 @@ describe('verify collector tests', () => { it('print payment receipt', async () => { const printMoneyReceiptSpy = vi.spyOn(PDFUtils, 'printMoneyReceipt') - const testComponent = await createTestComponent( + const {router: testComponent} = await createTestComponent( { url: '' }} />, - { store, history } + { store, initialEntries: [formatUrl('/', { + })] } ) testComponent.find('#print-receipt').hostNodes().simulate('click') @@ -132,23 +132,17 @@ describe('verify collector tests', () => { })*/ it('invalid declaration id', async () => { - await createTestComponent( - , - { store, history } - ) - expect(history.location.pathname).toEqual( + const { router } = await createTestComponent(, { + store, + path: PRINT_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(PRINT_CERTIFICATE_PAYMENT, { + registrationId: 'mockBirth', + eventType: EventType.Birth + }) + ] + }) + expect(router.state.location.pathname).toEqual( formatUrl(REGISTRAR_HOME_TAB, { tabId: WORKQUEUE_TABS.readyToPrint, selectorId: '' @@ -164,21 +158,18 @@ describe('verify collector tests', () => { }) it('when informant is collector', async () => { - const testComponent = await createTestComponent( - , + { + store, + path: PRINT_CERTIFICATE_PAYMENT, + initialEntries: [ + formatUrl(PRINT_CERTIFICATE_PAYMENT, { registrationId: 'mockDeath1234', eventType: EventType.Death - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#service').hostNodes().text()).toContain( diff --git a/packages/client/src/views/PrintCertificate/Payment.tsx b/packages/client/src/views/PrintCertificate/Payment.tsx index e902d10a88c..24bdb410736 100644 --- a/packages/client/src/views/PrintCertificate/Payment.tsx +++ b/packages/client/src/views/PrintCertificate/Payment.tsx @@ -28,7 +28,10 @@ import React from 'react' import { WrappedComponentProps as IntlShapeProps, injectIntl } from 'react-intl' import { connect } from 'react-redux' import { Navigate, useNavigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { withTheme } from 'styled-components' import { diff --git a/packages/client/src/views/PrintCertificate/ReviewCertificateAction.test.tsx b/packages/client/src/views/PrintCertificate/ReviewCertificateAction.test.tsx index 212699e25ed..213843f0f73 100644 --- a/packages/client/src/views/PrintCertificate/ReviewCertificateAction.test.tsx +++ b/packages/client/src/views/PrintCertificate/ReviewCertificateAction.test.tsx @@ -8,7 +8,6 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { Mock } from 'vitest' import * as React from 'react' import { createStore } from '@client/store' import { storeDeclaration, IDeclaration } from '@client/declarations' @@ -19,7 +18,7 @@ import { mockMarriageDeclarationData, flushPromises, loginAsFieldAgent, - createRouterProps + TestComponentWithRouteMock } from '@client/tests/util' import { ReviewCertificate } from './ReviewCertificateAction' import { ReactWrapper } from 'enzyme' @@ -27,8 +26,8 @@ import { IFormSectionData } from '@client/forms' import { EventType } from '@client/utils/gateway' import { cloneDeep } from 'lodash' import { waitForElement } from '@client/tests/wait-for-element' -import { push } from 'connected-react-router' -import { useParams } from 'react-router-dom' +import { formatUrl } from '@client/navigation' +import { REVIEW_CERTIFICATE } from '@client/navigation/routes' const deathDeclaration = { id: 'mockDeath1234', @@ -47,25 +46,22 @@ const deathDeclaration = { describe('when user wants to review death certificate', () => { it('displays the "Confirm & Print" button', async () => { - const { history, match } = createRouterProps( - '/', - { isNavigatedInsideApp: false }, - { - matchParams: { - registrationId: 'mockDeath1234', - eventType: EventType.Death - } - } - ) - ;(useParams as Mock).mockImplementation(() => match.params) - const { store } = createStore() loginAsFieldAgent(store) - const component = await createTestComponent(, { + const { component } = await createTestComponent(, { store, - history + path: REVIEW_CERTIFICATE, + initialEntries: [ + { + pathname: formatUrl(REVIEW_CERTIFICATE, { + registrationId: 'mockDeath1234', + eventType: EventType.Death + }), + state: { isNavigatedInsideApp: false } + } + ] }) // @ts-ignore @@ -79,8 +75,6 @@ describe('when user wants to review death certificate', () => { }) describe('back button behavior tests of review certificate action', () => { - let component: ReactWrapper - const mockBirthDeclarationData = { ...cloneDeep(mockDeclarationData), history: [ @@ -98,21 +92,7 @@ describe('back button behavior tests of review certificate action', () => { } it('takes user history back when navigated from inside app', async () => { - const { history, match } = createRouterProps( - '/previous-route', - { isNavigatedInsideApp: true }, - { - matchParams: { - registrationId: 'asdhdqe2472487jsdfsdf', - eventType: EventType.Birth - } - } - ) - ;(useParams as Mock).mockImplementation(() => match.params) - - const { store } = createStore(history) - - store.dispatch(push('/new-route', { isNavigatedInsideApp: true })) + const { store } = createStore() loginAsFieldAgent(store) const birthDeclaration = { @@ -124,28 +104,38 @@ describe('back button behavior tests of review certificate action', () => { // @ts-ignore storeDeclaration(birthDeclaration) ) - component = await createTestComponent(, { - store, - history - }) + const { component, router } = await createTestComponent( + , + { + store, + path: '*', + initialEntries: [ + { + pathname: formatUrl(REVIEW_CERTIFICATE, { + registrationId: 'asdhdqe2472487jsdfsdf', + eventType: EventType.Birth + }), + state: { isNavigatedInsideApp: true } + }, + { + pathname: '', + state: { isNavigatedInsideApp: true } + } + ] + } + ) component.find('#action_page_back_button').hostNodes().simulate('click') - expect(history.location.pathname).toBe('/previous-route') + expect(router.state.location.pathname).toBe( + formatUrl(REVIEW_CERTIFICATE, { + registrationId: 'asdhdqe2472487jsdfsdf', + eventType: EventType.Birth + }) + ) }) it('takes user to registration home when navigated from external link', async () => { - const { history, match } = createRouterProps( - '/previous-route', - { isNavigatedInsideApp: false }, - { - matchParams: { - registrationId: 'asdhdqe2472487jsdfsdf', - eventType: EventType.Birth - } - } - ) - ;(useParams as Mock).mockImplementation(() => match.params) - const { store } = createStore(history) + const { store } = createStore() loginAsFieldAgent(store) store.dispatch( @@ -156,14 +146,27 @@ describe('back button behavior tests of review certificate action', () => { event: EventType.Birth } as IDeclaration) ) - component = await createTestComponent(, { - store, - history - }) + const { component, router } = await createTestComponent( + , + { + store, + initialEntries: [ + { + pathname: formatUrl(REVIEW_CERTIFICATE, { + registrationId: 'asdhdqe2472487jsdfsdf', + eventType: EventType.Birth + }), + state: { isNavigatedInsideApp: false } + } + ] + } + ) component.find('#action_page_back_button').hostNodes().simulate('click') await flushPromises() - expect(history.location.pathname).toContain('/registration-home/print/') + expect(router.state.location.pathname).toContain( + '/registration-home/print/' + ) }) }) @@ -171,18 +174,7 @@ describe('when user wants to review birth certificate', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { history, match } = createRouterProps( - '/', - { isNavigatedInsideApp: false }, - { - matchParams: { - registrationId: 'asdhdqe2472487jsdfsdf', - eventType: EventType.Birth - } - } - ) - ;(useParams as Mock).mockImplementation(() => match.params) - const { store } = createStore(history) + const { store } = createStore() const mockBirthDeclarationData = cloneDeep(mockDeclarationData) mockBirthDeclarationData.registration.certificates[0] = { @@ -209,12 +201,26 @@ describe('when user wants to review birth certificate', () => { }) ) - component = await createTestComponent(, { - store, - history - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + path: REVIEW_CERTIFICATE, + initialEntries: [ + { + pathname: formatUrl(REVIEW_CERTIFICATE, { + registrationId: 'asdhdqe2472487jsdfsdf', + eventType: EventType.Birth + }), + state: { isNavigatedInsideApp: false } + } + ] + } + ) await flushPromises() - component.update() + testComponent.update() + + component = testComponent }) it('displays have the Continue and print Button', () => { @@ -251,18 +257,7 @@ describe('when user wants to review marriage certificate', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { history, match } = createRouterProps( - '/', - { isNavigatedInsideApp: false }, - { - matchParams: { - registrationId: '1234896128934719', - eventType: EventType.Birth - } - } - ) - ;(useParams as Mock).mockImplementation(() => match.params) - const { store } = createStore(history) + const { store } = createStore() const mockMarriageData = cloneDeep(mockMarriageDeclarationData) @@ -285,12 +280,26 @@ describe('when user wants to review marriage certificate', () => { }) ) - component = await createTestComponent(, { - store, - history - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + path: REVIEW_CERTIFICATE, + initialEntries: [ + { + pathname: formatUrl(REVIEW_CERTIFICATE, { + registrationId: '1234896128934719', + eventType: EventType.Birth + }), + state: { isNavigatedInsideApp: false } + } + ] + } + ) await flushPromises() - component.update() + testComponent.update() + + component = testComponent }) it('displays have the Continue and print Button', () => { diff --git a/packages/client/src/views/PrintCertificate/ReviewCertificateAction.tsx b/packages/client/src/views/PrintCertificate/ReviewCertificateAction.tsx index df9d9ed586c..d9d8dae0b83 100644 --- a/packages/client/src/views/PrintCertificate/ReviewCertificateAction.tsx +++ b/packages/client/src/views/PrintCertificate/ReviewCertificateAction.tsx @@ -49,7 +49,6 @@ const ReviewCertificateFrame = ({ const navigate = useNavigate() const back = () => { - // @TODO: CHECK if this needs to be changed const historyState = location.state const navigatedFromInsideApp = Boolean( historyState && historyState.isNavigatedInsideApp diff --git a/packages/client/src/views/PrintCertificate/VerifyCollector.test.tsx b/packages/client/src/views/PrintCertificate/VerifyCollector.test.tsx index 19c6acc5ba5..b2549e07d26 100644 --- a/packages/client/src/views/PrintCertificate/VerifyCollector.test.tsx +++ b/packages/client/src/views/PrintCertificate/VerifyCollector.test.tsx @@ -13,15 +13,17 @@ import { createStore } from '@client/store' import { createTestComponent, mockDeclarationData, - mockDeathDeclarationData + mockDeathDeclarationData, + TestComponentWithRouteMock } from '@client/tests/util' import { VerifyCollector } from './VerifyCollector' import { storeDeclaration } from '@client/declarations' import { EventType } from '@client/utils/gateway' -import { ReactWrapper } from 'enzyme' +import { formatUrl } from '@client/navigation' +import { VERIFY_COLLECTOR } from '@client/navigation/routes' describe('verify collector tests', () => { - const { store, history } = createStore() + const { store } = createStore() const birthDeclaration = { id: 'mockBirth1234', @@ -60,44 +62,39 @@ describe('verify collector tests', () => { }) it('when mother is collector renders idVerifier component', async () => { - const testComponent = await createTestComponent( - // @ts-ignore - , + { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + formatUrl(VERIFY_COLLECTOR, { registrationId: 'mockBirth1234', eventType: EventType.Birth, collector: 'mother' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) }) - it('should takes user go back', async () => { - const testComponent = await createTestComponent( - // @ts-ignore - { + const { component: testComponent, router } = await createTestComponent( + , + { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + '/', + formatUrl(VERIFY_COLLECTOR, { registrationId: 'mockBirth1234', eventType: EventType.Birth, collector: 'mother' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) testComponent @@ -111,127 +108,119 @@ describe('verify collector tests', () => { testComponent.update() - expect(history.location.pathname).toBe('/') + expect(router.state.location.pathname).toBe('/') }) describe('when informant is collector', () => { - let testComponent: ReactWrapper + let testComponent: TestComponentWithRouteMock beforeAll(() => { // @ts-ignore store.dispatch(storeDeclaration(deathDeclaration)) }) beforeEach(async () => { - testComponent = await createTestComponent( - // @ts-ignore - , - { store, history } - ) + testComponent = await createTestComponent(, { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + formatUrl(VERIFY_COLLECTOR, { + registrationId: 'mockDeath1234', + eventType: EventType.Death, + collector: 'informant' + }) + ] + }) }) it('renders idVerifier compomnent', () => { - expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) + expect( + testComponent.component.find('#idVerifier').hostNodes() + ).toHaveLength(1) }) it('clicking on yes button takes user to review certificate if there is no fee', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyPositive') .hostNodes() .simulate('click') - expect(history.location.pathname).toContain('review') + expect(testComponent.router.state.location.pathname).toContain('review') }) describe('when father is collector', () => { - let testComponent: ReactWrapper + let testComponent: TestComponentWithRouteMock beforeAll(() => { // @ts-ignore store.dispatch(storeDeclaration(birthDeclaration)) }) beforeEach(async () => { - testComponent = await createTestComponent( - // @ts-ignore - , - { store, history } - ) + testComponent = await createTestComponent(, { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + formatUrl(VERIFY_COLLECTOR, { + registrationId: 'mockBirth1234', + eventType: EventType.Death, + collector: 'father' + }) + ] + }) }) it('clicking on send button on modal takes user to payment if there is fee', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - testComponent + testComponent.component .find('#withoutVerificationPrompt') .find('#send') .hostNodes() .simulate('click') - expect(history.location.pathname).toContain('payment') + expect(testComponent.router.state.location.pathname).toContain( + 'payment' + ) }) }) it('clicking on no button shows up modal', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#withoutVerificationPrompt').hostNodes() + testComponent.component.find('#withoutVerificationPrompt').hostNodes() ).toHaveLength(1) }) it('clicking on cancel button hides the modal', () => { - testComponent + testComponent.component .find('#idVerifier') .find('#verifyNegative') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() - testComponent + testComponent.component .find('#withoutVerificationPrompt') .find('#cancel') .hostNodes() .simulate('click') - testComponent.update() + testComponent.component.update() expect( - testComponent.find('#withoutVerificationPrompt').hostNodes() + testComponent.component.find('#withoutVerificationPrompt').hostNodes() ).toHaveLength(0) }) }) @@ -244,22 +233,19 @@ describe('verify collector tests', () => { }) it('when informant is collector', async () => { - const testComponent = await createTestComponent( - // @ts-ignore - , + { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + formatUrl(VERIFY_COLLECTOR, { registrationId: 'mockDeath1234', eventType: EventType.Death, collector: 'informant' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) expect(testComponent.find('#idVerifier').hostNodes()).toHaveLength(1) diff --git a/packages/client/src/views/PrintCertificate/VerifyCollector.tsx b/packages/client/src/views/PrintCertificate/VerifyCollector.tsx index 4f9d735f445..294fdcc2894 100644 --- a/packages/client/src/views/PrintCertificate/VerifyCollector.tsx +++ b/packages/client/src/views/PrintCertificate/VerifyCollector.tsx @@ -31,7 +31,10 @@ import * as React from 'react' import { WrappedComponentProps as IntlShapeProps, injectIntl } from 'react-intl' import { connect } from 'react-redux' import { Navigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { getEventDate, getRegisteredDate, isFreeOfCost } from './utils' import { getOfflineData } from '@client/offline/selectors' import { IOfflineData } from '@client/offline/reducer' diff --git a/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.test.tsx b/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.test.tsx index cab89be3fd6..725f5b2ea85 100644 --- a/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.test.tsx +++ b/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.test.tsx @@ -17,21 +17,25 @@ import { inValidImageB64String, mockDeclarationData, mockDeathDeclarationData, - mockMarriageDeclarationData + mockMarriageDeclarationData, + TestComponentWithRouteMock, + flushPromises } from '@client/tests/util' import { ReactWrapper } from 'enzyme' import * as React from 'react' import { CollectorForm } from './CollectorForm' import { waitFor, waitForElement } from '@client/tests/wait-for-element' -import { createLocation, History } from 'history' import { merge } from 'lodash' import { EventType } from '@client/utils/gateway' import { storeDeclaration } from '@client/declarations' +import { + CERTIFICATE_COLLECTOR, + VERIFY_COLLECTOR +} from '@client/navigation/routes' +import { formatUrl } from '@client/navigation' import { vi } from 'vitest' let store: AppStore -let history: History -let location = createLocation('/') const declarationsHistory = [ { @@ -167,36 +171,34 @@ const marriageDeclaration = { beforeEach(() => { const s = createStore() store = s.store - history = s.history - location = createLocation('/') - history.location = location }) describe('Certificate collector test for a birth registration without father details', () => { describe('Test collector group', () => { let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] beforeEach(async () => { - //@ts-ignore + await flushPromises() store.dispatch(storeDeclaration(birthDeclaration)) - const testComponent = await createTestComponent( - , - { history, store } - ) + + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: VERIFY_COLLECTOR, + initialEntries: [ + '/', + formatUrl(VERIFY_COLLECTOR, { + groupId: 'user-view-group', + registrationId: birthDeclaration.id, + eventType: birthDeclaration.event + }) + ] + }) + component = testComponent + router = testRouter + await waitForElement(component, '#collector_form') }) @@ -222,33 +224,32 @@ describe('Certificate collector test for a birth registration without father det await new Promise((resolve) => { setTimeout(resolve, 500) }) + component.update() component.find('#confirm_form').hostNodes().simulate('click') await new Promise((resolve) => { setTimeout(resolve, 500) }) component.update() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/print/check/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth/father' ) }) - it('should redirects back to certificate collector option selection with father already selected', async () => { + it('should redirect back to certificate collector option selection with father already selected', async () => { + await flushPromises() component .find('#type_FATHER') .hostNodes() .simulate('change', { target: { value: 'FATHER' } }) - await new Promise((resolve) => { - setTimeout(resolve, 500) - }) + component.update() component.find('#confirm_form').hostNodes().simulate('click') - await new Promise((resolve) => { - setTimeout(resolve, 500) - }) + component.update() + component.find('#action_page_back_button').hostNodes().simulate('click') - component.update() + expect(component.find('#type_FATHER').hostNodes().props().checked).toBe( true ) @@ -269,7 +270,7 @@ describe('Certificate collector test for a birth registration without father det setTimeout(resolve, 500) }) component.update() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/cert/collector/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth/otherCertCollector' ) }) @@ -277,29 +278,30 @@ describe('Certificate collector test for a birth registration without father det describe('Test other collector group', () => { let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] beforeEach(async () => { /* * Who is collecting the certificate? */ + await flushPromises() store.dispatch(storeDeclaration(birthDeclaration)) - component = await createTestComponent( - , - { store, history } - ) + + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: CERTIFICATE_COLLECTOR, + initialEntries: [ + formatUrl(CERTIFICATE_COLLECTOR, { + groupId: 'otherCollector', + registrationId: birthDeclaration.id, + eventType: birthDeclaration.event + }) + ] + }) + + component = testComponent + router = testRouter const form = await waitForElement(component, '#collector_form') @@ -385,8 +387,9 @@ describe('Certificate collector test for a birth registration without father det 'input[name="affidavitFile"][type="file"]' ) }) + it('takes the user to affedavit view', async () => { - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/cert/collector/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth/affidavit' ) }) @@ -438,7 +441,7 @@ describe('Certificate collector test for a birth registration without father det component.find('#submit_confirm').hostNodes().simulate('click') - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/print/payment/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth' ) }) @@ -463,7 +466,7 @@ describe('Certificate collector test for a birth registration without father det component.find('#noAffidavitAgreementConfirmationModal').hostNodes() ).toHaveLength(1) component.find('#submit_confirm').hostNodes().simulate('click') - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/review/6a5fd35d-01ec-4c37-976e-e055107a74a1/birth' ) }) @@ -492,31 +495,28 @@ describe('Certificate collector test for a birth registration without father det }) describe('Certificate collector test for a birth registration with father details', () => { - const { store, history } = createStore() - const mockLocation: any = vi.fn() + const { store } = createStore() describe('Test collector group', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { + await flushPromises() store.dispatch(storeDeclaration(birthDeclaration)) - const testComponent = await createTestComponent( - , - { store, history } + const { component: testComponent } = await createTestComponent( + , + { + store, + path: CERTIFICATE_COLLECTOR, + initialEntries: [ + formatUrl(CERTIFICATE_COLLECTOR, { + groupId: 'collector', + registrationId: birthDeclaration.id, + eventType: birthDeclaration.event + }) + ] + } ) component = testComponent @@ -532,29 +532,27 @@ describe('Certificate collector test for a birth registration with father detail describe('Certificate collector test for a death registration', () => { describe('Test collector group', () => { let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] beforeEach(async () => { + await flushPromises() store.dispatch(storeDeclaration(deathDeclaration)) - const testComponent = await createTestComponent( - , - { store, history } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: CERTIFICATE_COLLECTOR, + initialEntries: [ + formatUrl(CERTIFICATE_COLLECTOR, { + groupId: 'collector', + registrationId: deathDeclaration.id, + eventType: deathDeclaration.event + }) + ] + }) component = testComponent + router = testRouter }) it('informant will be spouse', async () => { @@ -574,7 +572,7 @@ describe('Certificate collector test for a death registration', () => { const $confirm = await waitForElement(component, '#confirm_form') $confirm.hostNodes().simulate('click') - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/review/16ff35e1-3f92-4db3-b812-c402e609fb00/death' ) }) @@ -584,32 +582,30 @@ describe('Certificate collector test for a death registration', () => { describe('Certificate collector test for a marriage registration', () => { describe('Test collector group', () => { let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] beforeEach(async () => { + await flushPromises() store.dispatch(storeDeclaration(marriageDeclaration)) - const testComponent = await createTestComponent( - , - { store, history } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: CERTIFICATE_COLLECTOR, + initialEntries: [ + formatUrl(CERTIFICATE_COLLECTOR, { + groupId: 'collector', + registrationId: marriageDeclaration.id, + eventType: marriageDeclaration.event + }) + ] + }) component = testComponent + router = testRouter }) - it('informant will be grrom', async () => { + it('informant will be groom', async () => { const element = await waitForElement(component, '#type_INFORMANT_GROOM') expect(element.hostNodes()).toHaveLength(1) }) @@ -631,7 +627,7 @@ describe('Certificate collector test for a marriage registration', () => { const $confirm = await waitForElement(component, '#confirm_form') $confirm.hostNodes().simulate('click') - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/review/18ff35e1-3d92-4db3-b815-c4d2e609fb23/marriage' ) }) @@ -643,27 +639,30 @@ describe('Certificate collector test for a birth registration without father and let component: ReactWrapper<{}, {}> beforeEach(async () => { + await flushPromises() //@ts-ignore delete birthDeclaration['data']['father'] store.dispatch(storeDeclaration(birthDeclaration)) - const testComponent = await createTestComponent( - , - { store, history } + await flushPromises() + store.dispatch(storeDeclaration(marriageDeclaration)) + + const { component: testComponent } = await createTestComponent( + , + { + store, + path: CERTIFICATE_COLLECTOR, + initialEntries: [ + formatUrl(CERTIFICATE_COLLECTOR, { + groupId: 'collector', + registrationId: birthDeclaration.id, + eventType: birthDeclaration.event + }) + ] + } ) + component = testComponent + await waitForElement(component, '#collector_form') }) diff --git a/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.tsx b/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.tsx index 16a55d1d427..5a41b734540 100644 --- a/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.tsx +++ b/packages/client/src/views/PrintCertificate/collectorForm/CollectorForm.tsx @@ -76,7 +76,10 @@ import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { getUserDetails } from '@client/profile/profileSelectors' import { getRegisteringOfficeId } from '@client/utils/draftUtils' import { UserDetails } from '@client/utils/userUtils' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' const ErrorWrapper = styled.div` margin-top: -3px; diff --git a/packages/client/src/views/RecordAudit/ActionMenu.test.tsx b/packages/client/src/views/RecordAudit/ActionMenu.test.tsx index 17d8de94510..bacb3a9cfe8 100644 --- a/packages/client/src/views/RecordAudit/ActionMenu.test.tsx +++ b/packages/client/src/views/RecordAudit/ActionMenu.test.tsx @@ -124,8 +124,8 @@ const actionStatus = ( describe('View action', () => { const VIEW_SCOPES = SCOPES.NONE it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -143,14 +143,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -168,14 +168,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -193,14 +193,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Potential duplicate', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -219,14 +219,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Requires update', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -244,14 +244,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Validated', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -269,14 +269,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_DECLARATION]) @@ -294,14 +294,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_RECORD]) @@ -319,14 +319,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Registered + Printed in advance', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_RECORD]) @@ -344,14 +344,14 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) it('Pending correction', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.VIEW_RECORD]) @@ -369,7 +369,7 @@ describe('View action', () => { node?.simulate('click') - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( defaultDeclaration.id + '/viewRecord' ) }) @@ -378,8 +378,8 @@ describe('View action', () => { describe('Review action', () => { const REVIEW_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -401,8 +401,8 @@ describe('Review action', () => { }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -424,8 +424,8 @@ describe('Review action', () => { }) it('In review - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -447,12 +447,14 @@ describe('Review action', () => { await flushPromises() - expect(window.location.href).toContain('reviews/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'reviews/' + defaultDeclaration.id + ) }) it('In review - Not downloaded - Has Scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REVIEW_DECLARATION]) @@ -470,8 +472,8 @@ describe('Review action', () => { }) it('In review - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REVIEW_DECLARATION]) @@ -489,8 +491,8 @@ describe('Review action', () => { }) it('Potential duplicate - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -511,8 +513,8 @@ describe('Review action', () => { }) it('Potential duplicate - Not downloaded - Has Scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -533,8 +535,8 @@ describe('Review action', () => { }) it('Potential duplicate - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -557,12 +559,14 @@ describe('Review action', () => { await flushPromises() - expect(window.location.href).toContain('reviews/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'reviews/' + defaultDeclaration.id + ) }) it('Requires update', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REVIEW_DECLARATION]) @@ -580,8 +584,8 @@ describe('Review action', () => { }) it('Validated - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -603,12 +607,14 @@ describe('Review action', () => { await flushPromises() - expect(window.location.href).toContain('reviews/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'reviews/' + defaultDeclaration.id + ) }) it('Validated - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REVIEW_DECLARATION]) @@ -626,8 +632,8 @@ describe('Review action', () => { }) it('Validated - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REVIEW_DECLARATION]) @@ -645,8 +651,8 @@ describe('Review action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -668,8 +674,8 @@ describe('Review action', () => { }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -691,8 +697,8 @@ describe('Review action', () => { }) it('Registered + Printed in advance', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -714,8 +720,8 @@ describe('Review action', () => { }) it('Pending correction - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -736,14 +742,14 @@ describe('Review action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( 'review-correction/' + defaultDeclaration.id ) }) it('Pending correction - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -763,8 +769,8 @@ describe('Review action', () => { }) it('Pending correction - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ @@ -787,8 +793,8 @@ describe('Review action', () => { describe('Update action', () => { const UPDATE_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -809,12 +815,14 @@ describe('Update action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain('drafts/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'drafts/' + defaultDeclaration.id + ) }) it('In progress - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -835,12 +843,14 @@ describe('Update action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain('reviews/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'reviews/' + defaultDeclaration.id + ) }) it('In progress - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -858,8 +868,8 @@ describe('Update action', () => { }) it('In progress - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -877,8 +887,8 @@ describe('Update action', () => { }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -896,8 +906,8 @@ describe('Update action', () => { }) it('Potential duplicate', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -916,8 +926,8 @@ describe('Update action', () => { }) it('Requires update - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -939,12 +949,14 @@ describe('Update action', () => { await flushPromises() - expect(window.location.href).toContain('reviews/' + defaultDeclaration.id) + expect(router.state.location.pathname).toContain( + 'reviews/' + defaultDeclaration.id + ) }) it('Requires update - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -962,8 +974,8 @@ describe('Update action', () => { }) it('Requires update - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -981,8 +993,8 @@ describe('Update action', () => { }) it('Validated', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -1000,8 +1012,8 @@ describe('Update action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -1019,8 +1031,8 @@ describe('Update action', () => { }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -1038,8 +1050,8 @@ describe('Update action', () => { }) it('Registered + Printed in advance', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -1057,8 +1069,8 @@ describe('Update action', () => { }) it('Pending correction - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.UPDATE_DECLARATION]) @@ -1079,8 +1091,8 @@ describe('Update action', () => { describe('Archive action', () => { const ARCHIVE_SCOPES = ['validate', 'register'] as any as Scope it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1098,9 +1110,9 @@ describe('Archive action', () => { }) it('In progress - Downloaded', async () => { - const { store, history } = createStore() + const { store } = createStore() const toggleDisplayDialogMock = vi.fn() - const component = await createTestComponent( + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={toggleDisplayDialogMock} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1121,8 +1133,8 @@ describe('Archive action', () => { }) it('In progress - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1140,8 +1152,8 @@ describe('Archive action', () => { }) it('In progress - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1159,9 +1171,9 @@ describe('Archive action', () => { }) it('In review - Downloaded', async () => { - const { store, history } = createStore() + const { store } = createStore() const toggleDisplayDialogMock = vi.fn() - const component = await createTestComponent( + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={toggleDisplayDialogMock} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1182,8 +1194,8 @@ describe('Archive action', () => { }) it('In review - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1201,8 +1213,8 @@ describe('Archive action', () => { }) it('In review - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1220,9 +1232,9 @@ describe('Archive action', () => { }) it('Requires update - Downloaded', async () => { - const { store, history } = createStore() + const { store } = createStore() const toggleDisplayDialogMock = vi.fn() - const component = await createTestComponent( + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={toggleDisplayDialogMock} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1243,8 +1255,8 @@ describe('Archive action', () => { }) it('Requires update - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1262,8 +1274,8 @@ describe('Archive action', () => { }) it('Requires update - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1281,9 +1293,9 @@ describe('Archive action', () => { }) it('Validated - Downloaded', async () => { - const { store, history } = createStore() + const { store } = createStore() const toggleDisplayDialogMock = vi.fn() - const component = await createTestComponent( + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={toggleDisplayDialogMock} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1304,8 +1316,8 @@ describe('Archive action', () => { }) it('Validated - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1323,8 +1335,8 @@ describe('Archive action', () => { }) it('Validated - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1342,8 +1354,8 @@ describe('Archive action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1361,8 +1373,8 @@ describe('Archive action', () => { }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1380,8 +1392,8 @@ describe('Archive action', () => { }) it('Registered + Printed in advance', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1399,8 +1411,8 @@ describe('Archive action', () => { }) it('Pending correction', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ARCHIVE_RECORD]) @@ -1421,8 +1433,8 @@ describe('Archive action', () => { describe('Reinstate action', () => { const REINSTATE_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REINSTATE_RECORD]) @@ -1440,9 +1452,9 @@ describe('Reinstate action', () => { }) it('Archived - Downloaded', async () => { - const { store, history } = createStore() + const { store } = createStore() const toggleDisplayDialogMock = vi.fn() - const component = await createTestComponent( + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={toggleDisplayDialogMock} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.REINSTATE_RECORD]) @@ -1462,8 +1474,8 @@ describe('Reinstate action', () => { }) it('Archived - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REINSTATE_RECORD]) @@ -1481,8 +1493,8 @@ describe('Reinstate action', () => { }) it('Archived - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REINSTATE_RECORD]) @@ -1500,8 +1512,8 @@ describe('Reinstate action', () => { }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.REINSTATE_RECORD]) @@ -1522,8 +1534,8 @@ describe('Reinstate action', () => { describe('Print action', () => { const PRINT_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1541,8 +1553,8 @@ describe('Print action', () => { }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1560,8 +1572,8 @@ describe('Print action', () => { }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1579,8 +1591,8 @@ describe('Print action', () => { }) it('Potential duplicate', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1599,8 +1611,8 @@ describe('Print action', () => { }) it('Requires update', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1618,8 +1630,8 @@ describe('Print action', () => { }) it('Validated', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1637,8 +1649,8 @@ describe('Print action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1656,8 +1668,8 @@ describe('Print action', () => { }) it('Registered - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1676,14 +1688,14 @@ describe('Print action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( 'cert/collector/' + defaultDeclaration.id ) }) it('Registered - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1701,8 +1713,8 @@ describe('Print action', () => { }) it('Registered - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1720,8 +1732,8 @@ describe('Print action', () => { }) it('Registered + Printed in advance', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1739,8 +1751,8 @@ describe('Print action', () => { }) it('Pending correction', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.PRINT_RECORD]) @@ -1761,8 +1773,8 @@ describe('Print action', () => { describe('Issue action', () => { const ISSUE_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1780,8 +1792,8 @@ describe('Issue action', () => { }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1799,8 +1811,8 @@ describe('Issue action', () => { }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1818,8 +1830,8 @@ describe('Issue action', () => { }) it('Potential duplicate', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1838,8 +1850,8 @@ describe('Issue action', () => { }) it('Requires update', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1857,8 +1869,8 @@ describe('Issue action', () => { }) it('Validated', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1876,8 +1888,8 @@ describe('Issue action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1895,8 +1907,8 @@ describe('Issue action', () => { }) it('Registered', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1914,8 +1926,8 @@ describe('Issue action', () => { }) it('Registered + Printed in advance - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1934,12 +1946,15 @@ describe('Issue action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain('issue/' + defaultDeclaration.id) + + expect(router.state.location.pathname).toContain( + 'issue/' + defaultDeclaration.id + ) }) it('Registered + Printed in advance - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1957,8 +1972,8 @@ describe('Issue action', () => { }) it('Registered + Printed in advance - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1976,8 +1991,8 @@ describe('Issue action', () => { }) it('Pending correction', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.ISSUE_CERTIFICATE]) @@ -1998,8 +2013,8 @@ describe('Issue action', () => { describe('Correct action', () => { const CORRECTION_SCOPES = SCOPES.RA it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2017,8 +2032,8 @@ describe('Correct action', () => { }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2036,8 +2051,8 @@ describe('Correct action', () => { }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2055,8 +2070,8 @@ describe('Correct action', () => { }) it('Potential duplicate', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { duplicates={['duplicate1']} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2075,8 +2090,8 @@ describe('Correct action', () => { }) it('Requires update', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2094,8 +2109,8 @@ describe('Correct action', () => { }) it('Validated', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2113,8 +2128,8 @@ describe('Correct action', () => { }) it('Archived', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2132,8 +2147,8 @@ describe('Correct action', () => { }) it('Registered - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2152,14 +2167,14 @@ describe('Correct action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( 'correction/' + defaultDeclaration.id ) }) it('Registered - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2177,8 +2192,8 @@ describe('Correct action', () => { }) it('Registered - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2196,8 +2211,8 @@ describe('Correct action', () => { }) it('Registered + Printed in advance - Does not have scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2215,8 +2230,8 @@ describe('Correct action', () => { }) it('Registered + Printed in advance - Not downloaded - Has scope', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2234,8 +2249,8 @@ describe('Correct action', () => { }) it('Registered + Printed in advance - Downloaded', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component, router } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2254,14 +2269,14 @@ describe('Correct action', () => { node?.simulate('click') await flushPromises() - expect(window.location.href).toContain( + expect(router.state.location.pathname).toContain( 'correction/' + defaultDeclaration.id ) }) it('Pending correction', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.CORRECT_RECORD]) @@ -2281,8 +2296,8 @@ describe('Correct action', () => { describe('Delete declaration action', () => { it('Draft', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status, node } = actionStatus(component, [ @@ -2305,8 +2320,8 @@ describe('Delete declaration action', () => { }) it('In progress', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftDeathDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.DELETE_DECLARATION]) @@ -2324,8 +2339,8 @@ describe('Delete declaration action', () => { }) it('In review', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status } = actionStatus(component, [ACTION.DELETE_DECLARATION]) @@ -2347,8 +2362,8 @@ describe('Unassign action', () => { const UNASSIGN_SCOPES = SCOPES.REGISTRAR const Assignment = 'Assigned to Kennedy Mweene at Ibombo District Office' it('Has scope - assigned to someone else', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status: assignmentStatus } = actionStatus(component, [Assignment]) @@ -2372,8 +2387,8 @@ describe('Unassign action', () => { }) it('Does not have scope - assigned to someone else', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status: assignmentStatus } = actionStatus(component, [Assignment]) @@ -2394,8 +2409,8 @@ describe('Unassign action', () => { }) it('Assigned to self', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status: assignmentStatus } = actionStatus(component, [Assignment]) @@ -2419,8 +2434,8 @@ describe('Unassign action', () => { }) it('Not assigned', async () => { - const { store, history } = createStore() - const component = await createTestComponent( + const { store } = createStore() + const { component } = await createTestComponent( { draft={draftBirthNotDownloaded} toggleDisplayDialog={() => {}} />, - { store, history } + { store } ) const { status: assignmentStatus } = actionStatus(component, [Assignment]) diff --git a/packages/client/src/views/RecordAudit/RecordAudit.test.tsx b/packages/client/src/views/RecordAudit/RecordAudit.test.tsx index cd4e8c289cf..8d902d0d8de 100644 --- a/packages/client/src/views/RecordAudit/RecordAudit.test.tsx +++ b/packages/client/src/views/RecordAudit/RecordAudit.test.tsx @@ -13,7 +13,6 @@ import * as React from 'react' import { createTestComponent, mockDeclarationData, - createRouterProps, flushPromises, mockDeathDeclarationData, mockMarriageDeclarationData, @@ -69,26 +68,22 @@ describe('Record audit summary for a draft birth declaration', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.dispatch(storeDeclaration(declaration)) - component = await createTestComponent( - , + { + store, + path: DECLARATION_RECORD_AUDIT, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'inProgressTab', declarationId: declaration.id - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'inProgressTab', - declarationId: declaration.id - } - } - )} - />, - { store, history } + }) + ] + } ) + component = testComponent }) it('Record Audit page loads properly', async () => { @@ -113,31 +108,27 @@ describe('Record audit summary for a draft death declaration', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const deathDeclaration = createDeclaration( EventType.Death, mockDeathDeclarationData ) store.dispatch(storeDeclaration(deathDeclaration)) - component = await createTestComponent( - , + { + store, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'inProgressTab', declarationId: deathDeclaration.id - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'inProgressTab', - declarationId: deathDeclaration.id - } - } - )} - />, - { store, history } + }) + ], + path: DECLARATION_RECORD_AUDIT + } ) + component = testComponent }) it('Record Audit page loads properly', async () => { @@ -162,31 +153,27 @@ describe('Record audit summary for a draft marriage declaration', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const marriageDeclaration = createDeclaration( EventType.Marriage, mockMarriageDeclarationData ) store.dispatch(storeDeclaration(marriageDeclaration)) - component = await createTestComponent( - , + { + store, + path: DECLARATION_RECORD_AUDIT, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'inProgressTab', declarationId: marriageDeclaration.id - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'inProgressTab', - declarationId: marriageDeclaration.id - } - } - )} - />, - { store, history } + }) + ] + } ) + component = testComponent }) it('Record Audit page loads properly', async () => { @@ -211,7 +198,7 @@ describe('Record audit summary for WorkQueue declarations', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.getState().workqueueState.workqueue.data.inProgressTab.results = [ { @@ -260,24 +247,20 @@ describe('Record audit summary for WorkQueue declarations', () => { } as GQLBirthEventSearchSet ] - component = await createTestComponent( - , + { + store, + path: DECLARATION_RECORD_AUDIT, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'inProgressTab', declarationId: 'db097901-feba-4f71-a1ae-d3d46289d2d5' - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'inProgressTab', - declarationId: 'db097901-feba-4f71-a1ae-d3d46289d2d5' - } - } - )} - />, - { store, history } + }) + ] + } ) + component = testComponent }) it('Record Audit page loads properly', async () => { @@ -317,7 +300,7 @@ describe('Record audit summary for GQLQuery', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const mocks = [ { @@ -355,24 +338,21 @@ describe('Record audit summary for GQLQuery', () => { } ] - component = await createTestComponent( - , + { + store, + path: DECLARATION_RECORD_AUDIT, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'search', declarationId: '956281c9-1f47-4c26-948a-970dd23c4094' - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'search', - declarationId: '956281c9-1f47-4c26-948a-970dd23c4094' - } - } - )} - />, - { store, history, graphqlMocks: mocks } + }) + ], + graphqlMocks: mocks + } ) + component = testComponent await flushPromises() component.update() @@ -413,7 +393,7 @@ describe('Record audit summary for unsuccesful GQLQuery', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const mocks = [ { @@ -426,24 +406,21 @@ describe('Record audit summary for unsuccesful GQLQuery', () => { } ] - component = await createTestComponent( - , + { + store, + path: DECLARATION_RECORD_AUDIT, + initialEntries: [ formatUrl(DECLARATION_RECORD_AUDIT, { tab: 'search', declarationId: '956281c9-1f47-4c26-948a-970dd23c4094' - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - tab: 'search', - declarationId: '956281c9-1f47-4c26-948a-970dd23c4094' - } - } - )} - />, - { store, history, graphqlMocks: mocks } + }) + ], + graphqlMocks: mocks + } ) + component = testComponent await flushPromises() component.update() diff --git a/packages/client/src/views/RecordAudit/RecordAudit.tsx b/packages/client/src/views/RecordAudit/RecordAudit.tsx index 13e72555a92..cbcba7ce708 100644 --- a/packages/client/src/views/RecordAudit/RecordAudit.tsx +++ b/packages/client/src/views/RecordAudit/RecordAudit.tsx @@ -98,7 +98,10 @@ import { UserDetails } from '@client/utils/userUtils' import { client } from '@client/utils/apolloClient' import { IReviewFormState } from '@client/forms/register/reviewReducer' import { ActionMenu } from './ActionMenu' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' const DesktopHeader = styled(Header)` @media (max-width: ${({ theme }) => theme.grid.breakpoints.lg}px) { diff --git a/packages/client/src/views/RegisterForm/DeclarationForm.test.tsx b/packages/client/src/views/RegisterForm/DeclarationForm.test.tsx index 34074ec538a..298b7d4dea8 100644 --- a/packages/client/src/views/RegisterForm/DeclarationForm.test.tsx +++ b/packages/client/src/views/RegisterForm/DeclarationForm.test.tsx @@ -8,42 +8,44 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ +import { + createDeclaration, + IDeclaration, + IUserData, + storeDeclaration +} from '@client/declarations' +import { formatUrl } from '@client/navigation' +import { DRAFT_BIRTH_PARENT_FORM } from '@client/navigation/routes' +import { storage } from '@client/storage' import { createTestApp, flushPromises, - userDetails, + getFileFromBase64String, + goToChildSection, goToDocumentsSection, goToFatherSection, goToMotherSection, - setPageVisibility, - getFileFromBase64String, - validImageB64String, + goToSection, selectOption, - goToSection + setPageVisibility, + userDetails, + validImageB64String } from '@client/tests/util' -import { - storeDeclaration, - createDeclaration, - IDeclaration, - IUserData -} from '@client/declarations' +import { waitForElement } from '@client/tests/wait-for-element' +import { EventType } from '@client/utils/gateway' import { ReactWrapper } from 'enzyme' -import { History } from 'history' +import { createMemoryRouter } from 'react-router-dom' import { Store } from 'redux' -import { storage } from '@client/storage' -import { EventType } from '@client/utils/gateway' -import { waitForElement } from '@client/tests/wait-for-element' -import { vi, Mock } from 'vitest' -import { DRAFT_BIRTH_PARENT_FORM } from '@client/navigation/routes' +import { Mock, vi } from 'vitest' -describe('when user has starts a new declaration', () => { +describe('when user starts a new declaration', () => { describe('In case of insecured page show unlock screen', () => { let draft: IDeclaration let app: ReactWrapper - let history: History let store: Store beforeEach(async () => { + await flushPromises() const userData: IUserData[] = [ { userID: userDetails.userMgntUserID, @@ -61,38 +63,45 @@ describe('when user has starts a new declaration', () => { ;(storage.getItem as Mock).mockImplementation( (param: keyof typeof indexedDB) => Promise.resolve(indexedDB[param]) ) - const testApp = await createTestApp() + + draft = createDeclaration(EventType.Birth) + + const testApp = await createTestApp( + { waitUntilOfflineCountryConfigLoaded: true }, + [ + formatUrl(DRAFT_BIRTH_PARENT_FORM, { + declarationId: draft.id.toString() + }) + ] + ) app = testApp.app - history = testApp.history store = testApp.store - draft = createDeclaration(EventType.Birth) await store.dispatch(storeDeclaration(draft)) }) it('renders unlock screen', async () => { - history.replace( - DRAFT_BIRTH_PARENT_FORM.replace(':declarationId', draft.id.toString()) - ) await waitForElement(app, '#unlockPage') }) }) describe('when secured', () => { let app: ReactWrapper - let history: History + let store: Store + let router: ReturnType beforeEach(async () => { const testApp = await createTestApp() app = testApp.app - history = testApp.history store = testApp.store + router = testApp.router }) describe('when user is in birth registration by parent informant view', () => { let draft: IDeclaration beforeEach(async () => { + await flushPromises() const data = { registration: { informantType: { @@ -112,20 +121,18 @@ describe('when user has starts a new declaration', () => { * so offline declarations wouldn't override the dispatched ones */ store.dispatch(storeDeclaration(draft)) - // TODO: SELECT_BIRTH_INFORMANT has been removed - history.replace( - DRAFT_BIRTH_PARENT_FORM.replace(':declarationId', draft.id.toString()) + + router.navigate( + formatUrl(DRAFT_BIRTH_PARENT_FORM, { + declarationId: draft.id.toString() + }) ) - await waitForElement(app, '#content-name') - app.find('#next_section').hostNodes().simulate('click') - app.find('#next_section').hostNodes().simulate('click') - await waitForElement(app, '#form_section_id_child-view-group') + await goToChildSection(app) }) describe('when user types in something and press continue', () => { beforeEach(async () => { - // await waitForElement(app, '#informant_parent_view') app .find('#firstNamesEng') .hostNodes() @@ -200,18 +207,7 @@ describe('when user has starts a new declaration', () => { describe('when user goes to documents page', () => { beforeEach(async () => { - app.find('#next_section').hostNodes().simulate('click') - await flushPromises() - app.update() - app.find('#next_section').hostNodes().simulate('click') - await flushPromises() - app.update() - app.find('#next_section').hostNodes().simulate('click') - await flushPromises() - app.update() - app.find('#next_section').hostNodes().simulate('click') - await flushPromises() - app.update() + await goToDocumentsSection(app) }) it('renders list of document upload field', async () => { const fileInputs = app @@ -323,7 +319,7 @@ describe('when user has starts a new declaration', () => { describe('when user clicks the "mother" page', () => { beforeEach(() => goToMotherSection(app)) it('changes to the mother details section', () => { - expect(window.location.href).toContain('mother') + expect(router.state.location.pathname).toContain('mother') }) it('hides everything with pinpad if is page loses focus', async () => { setPageVisibility(false) @@ -332,8 +328,9 @@ describe('when user has starts a new declaration', () => { }) describe('when user clicks the "father" page', () => { beforeEach(() => goToFatherSection(app)) + it('changes to the father details section', () => { - expect(window.location.href).toContain('father') + expect(router.state.location.pathname).toContain('father') }) }) describe('when user is in document page', () => { diff --git a/packages/client/src/views/RegisterForm/DeclarationForm.tsx b/packages/client/src/views/RegisterForm/DeclarationForm.tsx index 35253371dc7..eff028ec824 100644 --- a/packages/client/src/views/RegisterForm/DeclarationForm.tsx +++ b/packages/client/src/views/RegisterForm/DeclarationForm.tsx @@ -9,10 +9,7 @@ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ import * as React from 'react' -import { - RegisterForm, - RouteProps -} from '@opencrvs/client/src/views/RegisterForm/RegisterForm' +import { RegisterForm } from '@opencrvs/client/src/views/RegisterForm/RegisterForm' import { DRAFT_BIRTH_PARENT_FORM_PAGE_GROUP, DRAFT_DEATH_FORM_PAGE_GROUP, @@ -26,7 +23,10 @@ import { IForm } from '@client/forms' import { EventType } from '@client/utils/gateway' import { IDeclaration } from '@client/declarations' import { Navigate } from 'react-router-dom' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' interface IFormProps { declaration?: IDeclaration @@ -51,7 +51,7 @@ const DeclarationFormView = (props: RouteComponentProps) => { return } -function mapStatetoProps(state: IStoreState, props: RouteProps) { +function mapStatetoProps(state: IStoreState, props: RouteComponentProps) { const declaration = state.declarationsState.declarations.find( ({ id }) => id === props.router.params.declarationId ) diff --git a/packages/client/src/views/RegisterForm/PreviewForm.test.tsx b/packages/client/src/views/RegisterForm/PreviewForm.test.tsx index 4a13bd9ecd9..ebdb1b7f3bd 100644 --- a/packages/client/src/views/RegisterForm/PreviewForm.test.tsx +++ b/packages/client/src/views/RegisterForm/PreviewForm.test.tsx @@ -30,7 +30,6 @@ import { createReviewDeclaration } from '@client/declarations' import { ReactWrapper } from 'enzyme' -import { History } from 'history' import { Store } from 'redux' import { EventType } from '@client/utils/gateway' import { v4 as uuid } from 'uuid' @@ -45,16 +44,27 @@ import { marriageReviewDraftData } from '@client/tests/mock-drafts' import { vi } from 'vitest' +import { formatUrl } from '@client/navigation' +import { createBrowserRouter } from 'react-router-dom' describe('when user is previewing the form data', () => { let app: ReactWrapper - let history: History + let router: ReturnType let store: Store beforeEach(async () => { - const testApp = await createTestApp() + const testApp = await createTestApp( + { waitUntilOfflineCountryConfigLoaded: true }, + [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + event: 'death', + pageId: 'review' + }) + ] + ) app = testApp.app - history = testApp.history + + router = testApp.router store = testApp.store await waitForReady(app) }) @@ -73,14 +83,14 @@ describe('when user is previewing the form data', () => { customDraft = { id: uuid(), data, review: true, event: EventType.Death } store.dispatch(storeDeclaration(customDraft)) - history.replace( - REVIEW_EVENT_PARENT_FORM_PAGE.replace( - ':declarationId', - customDraft.id.toString() - ) - .replace(':event', 'death') - .replace(':pageId', 'review') + router.navigate( + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: customDraft.id.toString(), + event: 'death', + pageId: 'review' + }) ) + await waitForElement(app, '#readyDeclaration') }) @@ -108,7 +118,7 @@ describe('when user is previewing the form data', () => { app.find('#submit_reject_form').hostNodes().simulate('click') - expect(history.location.pathname).toEqual(REGISTRAR_HOME) + expect(router.state.location.pathname).toEqual(REGISTRAR_HOME) }) }) @@ -125,7 +135,7 @@ describe('when user is previewing the form data', () => { submissionStatus: SUBMISSION_STATUS[SUBMISSION_STATUS.DRAFT] } store.dispatch(storeDeclaration(customDraft)) - history.replace( + router.navigate( DRAFT_BIRTH_PARENT_FORM.replace( ':declarationId', customDraft.id.toString() @@ -161,7 +171,7 @@ describe('when user is previewing the form data', () => { }) it('should redirect to home page', () => { app.find('#submit_confirm').hostNodes().simulate('click') - expect(history.location.pathname).toBe(REGISTRAR_HOME) + expect(router.state.location.pathname).toBe(REGISTRAR_HOME) }) }) }) @@ -179,7 +189,7 @@ describe('when user is previewing the form data', () => { customDraft = { id: uuid(), data, review: true, event: EventType.Birth } store.dispatch(storeDeclaration(customDraft)) - history.replace( + router.navigate( REVIEW_EVENT_PARENT_FORM_PAGE.replace( ':declarationId', customDraft.id.toString() @@ -207,11 +217,11 @@ describe('when user is previewing the form data', () => { app.find('#submit_reject_form').hostNodes().simulate('click') - expect(history.location.pathname).toEqual(REGISTRAR_HOME) + expect(router.state.location.pathname).toEqual(REGISTRAR_HOME) }) }) - describe('when user is in the marriage review section', () => { + describe('when user is in the marriage review sqection', () => { let customDraft: IDeclaration const registerScopeToken = @@ -230,7 +240,7 @@ describe('when user is previewing the form data', () => { event: EventType.Marriage } store.dispatch(storeDeclaration(customDraft)) - history.replace( + router.navigate( REVIEW_EVENT_PARENT_FORM_PAGE.replace( ':declarationId', customDraft.id.toString() @@ -259,7 +269,7 @@ describe('when user is previewing the form data', () => { }) app.find('#submit_reject_form').hostNodes().simulate('click') - expect(history.location.pathname).toEqual(REGISTRAR_HOME) + expect(router.state.location.pathname).toEqual(REGISTRAR_HOME) }) }) @@ -279,7 +289,7 @@ describe('when user is previewing the form data', () => { customDraft.submissionStatus = SUBMISSION_STATUS[SUBMISSION_STATUS.DRAFT] store.dispatch(storeDeclaration(customDraft)) - history.replace( + router.navigate( REVIEW_EVENT_PARENT_FORM_PAGE.replace( ':declarationId', customDraft.id.toString() diff --git a/packages/client/src/views/RegisterForm/RegisterForm.init.test.tsx b/packages/client/src/views/RegisterForm/RegisterForm.init.test.tsx index fcd8c495a3a..ebab496119b 100644 --- a/packages/client/src/views/RegisterForm/RegisterForm.init.test.tsx +++ b/packages/client/src/views/RegisterForm/RegisterForm.init.test.tsx @@ -30,6 +30,7 @@ import { vi } from 'vitest' import { EventType, SystemRoleType, Status } from '@client/utils/gateway' import { storage } from '@client/storage' import { UserDetails } from '@client/utils/userUtils' +import { formatUrl } from '@client/navigation' describe('when user logs in', () => { // Some mock data const draft1 = createDeclaration(EventType.Birth) @@ -185,30 +186,29 @@ describe('when there is no user-data saved', () => { describe('when user is in the register form before initial draft load', () => { it('throws error when draft not found after initial drafts load', async () => { - const { store, history } = await createTestStore() + const { store } = await createTestStore() - const mock: any = vi.fn() const draft = createDeclaration(EventType.Birth) const form = await getRegisterFormFromStore(store, EventType.Birth) try { await createTestComponent( - // @ts-ignore , - { store, history } + { + store, + path: DRAFT_BIRTH_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE, { + declarationId: '', + pageId: '', + groupId: '' + }) + ] + } ) } catch (error) { expect(error).toBeInstanceOf(Error) diff --git a/packages/client/src/views/RegisterForm/RegisterForm.test.tsx b/packages/client/src/views/RegisterForm/RegisterForm.test.tsx index 57be0bf36f4..d252ac9a500 100644 --- a/packages/client/src/views/RegisterForm/RegisterForm.test.tsx +++ b/packages/client/src/views/RegisterForm/RegisterForm.test.tsx @@ -20,7 +20,8 @@ import { createTestStore, flushPromises, userDetails, - mockOfflineData + mockOfflineData, + TestComponentWithRouteMock } from '@client/tests/util' import { RegisterForm } from '@client/views/RegisterForm/RegisterForm' import { ReactWrapper } from 'enzyme' @@ -50,23 +51,22 @@ import { clone, cloneDeep } from 'lodash' import * as profileSelectors from '@client/profile/profileSelectors' import { getRegisterForm } from '@client/forms/register/declaration-selectors' import { waitForElement } from '@client/tests/wait-for-element' -import { History } from 'history' import { vi } from 'vitest' import { createClient } from '@client/utils/apolloClient' import { ApolloClient } from '@apollo/client' +import { formatUrl } from '@client/navigation' +import { createMemoryRouter } from 'react-router-dom' describe('when user is in the register form for birth event', () => { - let component: ReactWrapper<{}, {}> + let component: TestComponentWithRouteMock let store: AppStore - let history: History let client: ApolloClient<{}> describe('when user is in the mother section', () => { beforeEach(async () => { const storeContext = await createTestStore() store = storeContext.store - history = storeContext.history client = createClient(store) const draft = createDeclaration(EventType.Birth) @@ -74,29 +74,26 @@ describe('when user is in the register form for birth event', () => { store.dispatch(setInitialDeclarations()) store.dispatch(storeDeclaration(draft)) - const mock: any = vi.fn() const form = await getRegisterFormFromStore(store, EventType.Birth) const testComponent = await createTestComponent( // @ts-ignore , + { + store, + apolloClient: client, + path: DRAFT_BIRTH_PARENT_FORM_PAGE_GROUP, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE_GROUP, { declarationId: draft.id, pageId: 'mother', groupId: 'mother-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history, apolloClient: client } + }) + ] + } ) component = testComponent }) @@ -105,27 +102,37 @@ describe('when user is in the register form for birth event', () => { () => 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJkZWNsYXJlIiwiZGVtbyJdLCJpYXQiOjE1NjMyNTYyNDIsImV4cCI6MTU2Mzg2MTA0MiwiYXVkIjpbIm9wZW5jcnZzOmF1dGgtdXNlciIsIm9wZW5jcnZzOnVzZXItbWdudC11c2VyIiwib3BlbmNydnM6aGVhcnRoLXVzZXIiLCJvcGVuY3J2czpnYXRld2F5LXVzZXIiLCJvcGVuY3J2czpub3RpZmljYXRpb24tdXNlciIsIm9wZW5jcnZzOndvcmtmbG93LXVzZXIiLCJvcGVuY3J2czpzZWFyY2gtdXNlciIsIm9wZW5jcnZzOm1ldHJpY3MtdXNlciIsIm9wZW5jcnZzOnJlc291cmNlcy11c2VyIl0sImlzcyI6Im9wZW5jcnZzOmF1dGgtc2VydmljZSIsInN1YiI6IjVkMWM1YTJhNTgxNjM0MDBlZjFkMDEyOSJ9.hZu0em2JA0sl-5uzck4mn4HfYdzxSmgoERA8SbWRPXEmriSYjs4PEPk9StXF_Ed5kd53VlNF9xf39DDGWqyyn76gpcMPbHJAL8nqLV82hot8fgU1WtEk865U8-9oAxaVmxAsjpHayiuD6zfKuR-ixrLFdoRKP13LdORktFCQe5e7To2w7vXArjUb6SDpSHST4Fbkhg8vzOcykweSGiNlmoEVtLzkpamS6fcTGRHkNpb_Wk_AQW9TAdw6NqG5lDEAO10auNgJpKxO8X-DQKhvEfY5TbpblR51L_U8pUXpDCAvGegMLnwmfAIoH1hMj--Wd2JhqgUvj0YrlDKI99fntA' ) - component.update() - - component.find('#save-exit-btn').hostNodes().simulate('click') - component.update() - component.find('#confirm_save_exit').hostNodes().simulate('click') - component.update() + component.component.update() + + component.component.find('#save-exit-btn').hostNodes().simulate('click') + component.component.update() + component.component + .find('#confirm_save_exit') + .hostNodes() + .simulate('click') + component.component.update() await flushPromises() - expect(history.location.pathname).toEqual('/registration-home/progress/') + expect(component.router.state.location.pathname).toEqual( + '/registration-home/progress/' + ) }) it('takes registrar to declaration submitted page when save button is clicked', async () => { localStorage.getItem = vi.fn( () => 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsInBlcmZvcm1hbmNlIiwiY2VydGlmeSIsImRlbW8iXSwiaWF0IjoxNTYzOTcyOTQ0LCJleHAiOjE1NjQ1Nzc3NDQsImF1ZCI6WyJvcGVuY3J2czphdXRoLXVzZXIiLCJvcGVuY3J2czp1c2VyLW1nbnQtdXNlciIsIm9wZW5jcnZzOmhlYXJ0aC11c2VyIiwib3BlbmNydnM6Z2F0ZXdheS11c2VyIiwib3BlbmNydnM6bm90aWZpY2F0aW9uLXVzZXIiLCJvcGVuY3J2czp3b3JrZmxvdy11c2VyIiwib3BlbmNydnM6c2VhcmNoLXVzZXIiLCJvcGVuY3J2czptZXRyaWNzLXVzZXIiLCJvcGVuY3J2czpyZXNvdXJjZXMtdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1ZDFjNWEyYTU4MTYzNDAwZWYxZDAxMmIifQ.VrH31goeitKvLHQchy5HQJkQWjhK-cWisxSgQUXChK4MZQis9Ufzn7dWK3s2s0dSpnFqk-0Yj5cVlq7JgQVcniO26WhnSyXHYQk7DG-TSA5FXGYoKMhjMZCh5qOZTRaVI6yvnEsLKTYeNvkXKJ2wb6M9U5OWjUh1KGPexd9mSjUsUwZ5BDTvI0WjnBTgQ_a0-KhxjjypT8Y_VXiiY-KWLxuOpVGalv3P3nbH8dAUzEuzKsrq6q0MJsaJkgDliaz2pZd10JxnJE1VYUob2SNHFnmJnz8Llwe1lH4xa8rluIA6YBmxdkrU2VkhCBPD6VxGYRHrD3LKRa3Cgm1X0qNQTw' ) - component.find('#save-exit-btn').hostNodes().simulate('click') - component.update() - component.find('#confirm_save_exit').hostNodes().simulate('click') - component.update() + component.component.find('#save-exit-btn').hostNodes().simulate('click') + component.component.update() + component.component + .find('#confirm_save_exit') + .hostNodes() + .simulate('click') + component.component.update() await flushPromises() expect( - history.location.pathname.includes('/registration-home/progress') + component.router.state.location.pathname.includes( + '/registration-home/progress' + ) ).toBeTruthy() }) }) @@ -136,13 +143,11 @@ describe('when user is in the register form for death event', () => { let form: IForm let store: AppStore - let history: History let draft: ReturnType beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history draft = createDeclaration(EventType.Death) store.dispatch(setInitialDeclarations()) @@ -156,28 +161,24 @@ describe('when user is in the register form for death event', () => { // TODO: need to check if causeOfDeathNotice is needed or not // clonedForm.sections[2].notice = messages.causeOfDeathNotice clonedForm.sections[2].groups[0].ignoreSingleFieldView = true - const mock: any = vi.fn() - const testComponent = await createTestComponent( - // @ts-ignore + // const mock: any = vi.fn() + const { component: testComponent } = await createTestComponent( , + { + store, + path: DRAFT_DEATH_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_DEATH_FORM_PAGE, { declarationId: draft.id, pageId: 'deathEvent', groupId: 'death-event-details' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = testComponent }) @@ -195,13 +196,12 @@ describe('when user is in the register form for marriage event', () => { let form: IForm let store: AppStore - let history: History + let draft: ReturnType beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history draft = createDeclaration(EventType.Marriage) store.dispatch(setInitialDeclarations()) @@ -214,28 +214,24 @@ describe('when user is in the register form for marriage event', () => { const clonedForm = cloneDeep(form) clonedForm.sections[2].optional = true clonedForm.sections[2].groups[0].ignoreSingleFieldView = true - const mock: any = vi.fn() - const testComponent = await createTestComponent( - // @ts-ignore + + const { component: testComponent } = await createTestComponent( , + { + store, + path: DRAFT_MARRIAGE_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_MARRIAGE_FORM_PAGE, { declarationId: draft.id, pageId: 'marriageEvent', groupId: 'marriage-event-details' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = testComponent }) @@ -249,16 +245,15 @@ describe('when user is in the register form for marriage event', () => { }) describe('when user is in the register form preview section', () => { - let component: ReactWrapper<{}, {}> + let component: TestComponentWithRouteMock let store: AppStore - let history: History + const mock = vi.fn() beforeEach(async () => { mock.mockReset() const storeContext = await createTestStore() store = storeContext.store - history = storeContext.history const draft = createDeclaration(EventType.Birth) draft.data = { @@ -287,38 +282,38 @@ describe('when user is in the register form preview section', () => { const form = await getRegisterFormFromStore(store, EventType.Birth) const testComponent = await createTestComponent( - // @ts-ignore , + { + store, + path: DRAFT_BIRTH_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE, { declarationId: draft.id, pageId: 'preview', groupId: 'preview-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = testComponent }) it('submit button will be enabled when even if form is not fully filled-up', () => { - expect(component.find('#submit_form').hostNodes().prop('disabled')).toBe( - false - ) + expect( + component.component.find('#submit_form').hostNodes().prop('disabled') + ).toBe(false) }) it('Displays submit confirm modal when submit button is clicked', () => { - component.find('#submit_form').hostNodes().simulate('click') + component.component.find('#submit_form').hostNodes().simulate('click') - expect(component.find('#submit_confirm').hostNodes()).toHaveLength(1) + expect( + component.component.find('#submit_confirm').hostNodes() + ).toHaveLength(1) }) describe('User in the Preview section for submitting the Form', () => { @@ -335,50 +330,52 @@ describe('when user is in the register form preview section', () => { const nform = getRegisterForm(store.getState())[EventType.Birth] const nTestComponent = await createTestComponent( - // @ts-ignore , + { + store, + path: DRAFT_BIRTH_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE, { declarationId: nDeclaration.id, pageId: 'preview', groupId: 'preview-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = nTestComponent }) it('should be able to submit the form', () => { - component.find('#submit_form').hostNodes().simulate('click') - component.update() + component.component.find('#submit_form').hostNodes().simulate('click') + component.component.update() - const cancelBtn = component.find('#cancel-btn').hostNodes() + const cancelBtn = component.component.find('#cancel-btn').hostNodes() expect(cancelBtn.length).toEqual(1) cancelBtn.simulate('click') - component.update() + component.component.update() - expect(component.find('#submit_confirm').hostNodes().length).toEqual(0) - expect(component.find('#submit_form').hostNodes().length).toEqual(1) + expect( + component.component.find('#submit_confirm').hostNodes().length + ).toEqual(0) + expect( + component.component.find('#submit_form').hostNodes().length + ).toEqual(1) - component.find('#submit_form').hostNodes().simulate('click') - component.update() + component.component.find('#submit_form').hostNodes().simulate('click') + component.component.update() - const confirmBtn = component.find('#submit_confirm').hostNodes() + const confirmBtn = component.component.find('#submit_confirm').hostNodes() expect(confirmBtn.length).toEqual(1) confirmBtn.simulate('click') - component.update() - expect(history.location.pathname).toBe(HOME) + component.component.update() + expect(component.router.state.location.pathname).toBe(HOME) }) }) }) @@ -386,7 +383,7 @@ describe('when user is in the register form preview section', () => { describe('when user is in the register form review section', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = await createTestStore() + const { store } = await createTestStore() // @ts-ignore const declaration = createReviewDeclaration( uuid(), @@ -395,32 +392,28 @@ describe('when user is in the register form review section', () => { ) store.dispatch(setInitialDeclarations()) store.dispatch(storeDeclaration(declaration)) - const mock: any = vi.fn() + vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['register']) const form = await getReviewFormFromStore(store, EventType.Birth) - const testComponent = await createTestComponent( - // @ts-ignore + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: declaration.id, pageId: 'review', groupId: 'review-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = testComponent }) @@ -437,8 +430,9 @@ describe('when user is in the register form review section', () => { describe('when user is in the register form from review edit', () => { let component: ReactWrapper<{}, {}> + let router: ReturnType beforeEach(async () => { - const { store, history } = await createTestStore() + const { store } = await createTestStore() // @ts-ignore const declaration = createReviewDeclaration( uuid(), @@ -447,34 +441,33 @@ describe('when user is in the register form from review edit', () => { ) store.dispatch(setInitialDeclarations()) store.dispatch(storeDeclaration(declaration)) - const mock: any = vi.fn() + vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['register']) const form = await getReviewFormFromStore(store, EventType.Birth) - const testComponent = await createTestComponent( - // @ts-ignore - , - { store, history } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + '/', + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'mother', + groupId: 'mother-view-group' + }) + ] + } + ) component = testComponent + router = testRouter }) it('should redirect to review page when back button is clicked', async () => { @@ -482,7 +475,7 @@ describe('when user is in the register form from review edit', () => { backButton.hostNodes().simulate('click') component.update() await flushPromises() - expect(window.location.href).toContain('/review') + expect(router.state.location.pathname).toContain('/review') }) }) @@ -491,7 +484,7 @@ describe('when user is in the register form from sent for review edit', () => { let testAppStore: AppStore beforeEach(async () => { Date.now = vi.fn(() => 1582525224324) - const { store, history } = await createTestStore() + const { store } = await createTestStore() // @ts-ignore const declaration = createReviewDeclaration( uuid(), @@ -501,32 +494,28 @@ describe('when user is in the register form from sent for review edit', () => { ) store.dispatch(setInitialDeclarations()) store.dispatch(storeDeclaration(declaration)) - const mock: any = vi.fn() + vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['register']) const form = await getReviewFormFromStore(store, EventType.Birth) - const testComponent = await createTestComponent( - // @ts-ignore + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: declaration.id, pageId: 'mother', groupId: 'mother-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = testComponent testAppStore = store @@ -575,17 +564,13 @@ describe('when user is in the register form from sent for review edit', () => { describe('When user is in Preview section death event', () => { let store: AppStore - let history: History - let component: ReactWrapper<{}, {}> + let component: TestComponentWithRouteMock let deathDraft: IDeclaration let deathForm: IForm - const mock: any = vi.fn() - beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history const draft = createDeclaration(EventType.Death) store.dispatch(setInitialDeclarations()) @@ -606,26 +591,22 @@ describe('When user is in Preview section death event', () => { deathForm = await getRegisterFormFromStore(store, EventType.Death) const nTestComponent = await createTestComponent( - // @ts-ignore , + { + store, + path: DRAFT_BIRTH_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE, { declarationId: deathDraft.id, pageId: 'preview', groupId: 'preview-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = nTestComponent }) @@ -655,15 +636,15 @@ describe('When user is in Preview section death event', () => { }) it('Should be able to submit the form', () => { - component.find('#submit_form').hostNodes().simulate('click') + component.component.find('#submit_form').hostNodes().simulate('click') - const confirmBtn = component.find('#submit_confirm').hostNodes() + const confirmBtn = component.component.find('#submit_confirm').hostNodes() expect(confirmBtn.length).toEqual(1) confirmBtn.simulate('click') - component.update() + component.component.update() - expect(history.location.pathname).toBe(HOME) + expect(component.router.state.location.pathname).toBe(HOME) }) it('Check if death location as hospital is parsed properly', () => { const hospitalLocatioMockDeathDeclarationData = clone( @@ -720,17 +701,14 @@ describe('When user is in Preview section death event', () => { }) describe('When user is in Preview section death event in offline mode', () => { - let component: ReactWrapper<{}, {}> + let component: TestComponentWithRouteMock let deathDraft let deathForm: IForm let store: AppStore - let history: History - - const mock: any = vi.fn() beforeEach(async () => { const testStore = await createTestStore() - history = testStore.history + store = testStore.store const draft = createDeclaration(EventType.Death) @@ -755,56 +733,49 @@ describe('When user is in Preview section death event in offline mode', () => { deathForm = await getRegisterFormFromStore(store, EventType.Death) const nTestComponent = await createTestComponent( - // @ts-ignore , + { + store, + path: DRAFT_BIRTH_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_BIRTH_PARENT_FORM_PAGE, { declarationId: deathDraft.id, pageId: 'preview', groupId: 'preview-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = nTestComponent }) it('Should be able to submit the form', async () => { - component.find('#submit_form').hostNodes().simulate('click') + component.component.find('#submit_form').hostNodes().simulate('click') - const confirmBtn = component.find('#submit_confirm').hostNodes() + const confirmBtn = component.component.find('#submit_confirm').hostNodes() expect(confirmBtn.length).toEqual(1) confirmBtn.simulate('click') - component.update() + component.component.update() - expect(history.location.pathname).toBe(HOME) + expect(component.router.state.location.pathname).toBe(HOME) }) }) describe('When user is in Preview section marriage event', () => { let store: AppStore - let history: History - let component: ReactWrapper<{}, {}> + + let component: TestComponentWithRouteMock let marriageDraft let marriageForm: IForm - const mock: any = vi.fn() - beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history const draft = createDeclaration(EventType.Death) store.dispatch(setInitialDeclarations()) @@ -827,24 +798,21 @@ describe('When user is in Preview section marriage event', () => { const nTestComponent = await createTestComponent( // @ts-ignore , + { + store, + path: DRAFT_MARRIAGE_FORM_PAGE, + initialEntries: [ + formatUrl(DRAFT_MARRIAGE_FORM_PAGE, { declarationId: marriageDraft.id, pageId: 'preview', groupId: 'preview-view-group' - }, - isExact: true, - path: '', - url: '' - }} - />, - { store, history } + }) + ] + } ) component = nTestComponent }) @@ -874,14 +842,14 @@ describe('When user is in Preview section marriage event', () => { }) it('Should be able to submit the form', () => { - component.find('#submit_form').hostNodes().simulate('click') + component.component.find('#submit_form').hostNodes().simulate('click') - const confirmBtn = component.find('#submit_confirm').hostNodes() + const confirmBtn = component.component.find('#submit_confirm').hostNodes() expect(confirmBtn.length).toEqual(1) confirmBtn.simulate('click') - component.update() + component.component.update() - expect(history.location.pathname).toBe(HOME) + expect(component.router.state.location.pathname).toBe(HOME) }) }) diff --git a/packages/client/src/views/RegisterForm/RegisterForm.tsx b/packages/client/src/views/RegisterForm/RegisterForm.tsx index ac6e7a92988..ec339171503 100644 --- a/packages/client/src/views/RegisterForm/RegisterForm.tsx +++ b/packages/client/src/views/RegisterForm/RegisterForm.tsx @@ -106,7 +106,10 @@ import { STATUSTOCOLOR } from '@client/views/RecordAudit/RecordAudit' import { DuplicateFormTabs } from '@client/views/RegisterForm/duplicate/DuplicateFormTabs' import { ReviewSection } from '@client/views/RegisterForm/review/ReviewSection' import { Text } from '@opencrvs/components/lib/Text' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' import { useNavigate } from 'react-router-dom' import styled from 'styled-components' diff --git a/packages/client/src/views/RegisterForm/ReviewForm.test.tsx b/packages/client/src/views/RegisterForm/ReviewForm.test.tsx index df33326f66d..117d690529c 100644 --- a/packages/client/src/views/RegisterForm/ReviewForm.test.tsx +++ b/packages/client/src/views/RegisterForm/ReviewForm.test.tsx @@ -28,14 +28,16 @@ import { mockUserResponseWithName, getReviewFormFromStore, createTestStore, - mockDeathDeclarationData + mockDeathDeclarationData, + flushPromises } from '@client/tests/util' import { v4 as uuid } from 'uuid' import { ReviewForm } from '@client/views/RegisterForm/ReviewForm' -import { History } from 'history' + import { WORKQUEUE_TABS } from '@client/components/interface/Navigation' import { birthDraftData } from '@client/tests/mock-drafts' import { vi, Mock } from 'vitest' +import { formatUrl } from '@client/navigation' const declareScope = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJpYXQiOjE1MzMxOTUyMjgsImV4cCI6MTU0MzE5NTIyNywiYXVkIjpbImdhdGV3YXkiXSwic3ViIjoiMSJ9.G4KzkaIsW8fTkkF-O8DI0qESKeBI332UFlTXRis3vJ6daisu06W5cZsgYhmxhx_n0Q27cBYt2OSOnjgR72KGA5IAAfMbAJifCul8ib57R4VJN8I90RWqtvA0qGjV-sPndnQdmXzCJx-RTumzvr_vKPgNDmHzLFNYpQxcmQHA-N8li-QHMTzBHU4s9y8_5JOCkudeoTMOd_1021EDAQbrhonji5V1EOSY2woV5nMHhmq166I1L0K_29ngmCqQZYi1t6QBonsIowlXJvKmjOH5vXHdCCJIFnmwHmII4BK-ivcXeiVOEM_ibfxMWkAeTRHDshOiErBFeEvqd6VWzKvbKAH0UY-Rvnbh4FbprmO4u4_6Yd2y2HnbweSo-v76dVNcvUS0GFLFdVBt0xTay-mIeDy8CKyzNDOWhmNUvtVi9mhbXYfzzEkwvi9cWwT1M8ZrsWsvsqqQbkRCyBmey_ysvVb5akuabenpPsTAjiR8-XU2mdceTKqJTwbMU5gz-8fgulbTB_9TNJXqQlH7tyYXMWHUY3uiVHWg2xgjRiGaXGTiDgZd01smYsxhVnPAddQOhqZYCrAgVcT1GBFVvhO7CC-rhtNlLl21YThNNZNpJHsCgg31WA9gMQ_2qAJmw2135fAyylO8q7ozRUvx46EezZiPzhCkPMeELzLhQMEIqjo' @@ -255,15 +257,13 @@ mockFetchUserDetails.mockReturnValue(mockUserResponseWithName) queries.fetchUserDetails = mockFetchUserDetails describe('ReviewForm tests', () => { const scope = ['register'] - const mock: any = vi.fn() + let form: IForm let store: AppStore - let history: History beforeEach(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history form = await getReviewFormFromStore(store, EventType.Birth) getItem.mockReturnValue(registerScopeToken) @@ -271,32 +271,32 @@ describe('ReviewForm tests', () => { }) it('Shared contact phone number should be set properly', async () => { - const testComponent = await createTestComponent( + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await new Promise((resolve) => setTimeout(resolve, 100)) + store.dispatch(storeDeclaration(birthDeclaration)) + + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: birthDeclaration.id, pageId: 'review', event: birthDeclaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={birthDeclaration.id} - />, - { store, history } + }) + ] + } ) - store.dispatch(storeDeclaration(birthDeclaration)) - testComponent.update() const data = testComponent .find(RegisterForm) .prop('declaration') as IDeclaration @@ -307,29 +307,32 @@ describe('ReviewForm tests', () => { ).registrationPhone ).toBe('+8801711111111') }) + it('when registration has attachment', async () => { - const testComponent = await createTestComponent( + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await new Promise((resolve) => setTimeout(resolve, 100)) + store.dispatch(storeDeclaration(birthDeclaration)) + + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: birthDeclaration.id, pageId: 'review', event: birthDeclaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={birthDeclaration.id} - />, - { store, history } + }) + ] + } ) store.dispatch(storeDeclaration(birthDeclaration)) @@ -350,31 +353,32 @@ describe('ReviewForm tests', () => { ]) }) it('check registration', async () => { - const testComponent = await createTestComponent( + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + store.dispatch(storeDeclaration(birthDeclaration)) + + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: birthDeclaration.id, pageId: 'review', event: birthDeclaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={birthDeclaration.id} - />, - { store, history } + }) + ] + } ) - store.dispatch(storeDeclaration(birthDeclaration)) testComponent.update() const data = testComponent @@ -405,6 +409,7 @@ describe('ReviewForm tests', () => { certificates: [{}] }) }) + it('redirect to home when exit button is clicked', async () => { const declaration = createReviewDeclaration( uuid(), @@ -413,29 +418,10 @@ describe('ReviewForm tests', () => { RegStatus.InProgress ) - const testComponent = await createTestComponent( - , - { store, history } - ) + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + store.dispatch( getStorageDeclarationsSuccess( JSON.stringify({ @@ -446,13 +432,40 @@ describe('ReviewForm tests', () => { ) ) store.dispatch(storeDeclaration(declaration)) + + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'review', + event: declaration.event.toLowerCase() + }) + ] + } + ) + testComponent.update() testComponent.find('#exit-btn').hostNodes().simulate('click') testComponent.update() - expect(window.location.href).toContain('/progress') + expect(testRouter.state.location.pathname).toContain('/progress') }) it('redirect to review tab when exit button is clicked', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + const declaration = createReviewDeclaration( uuid(), birthDraftData, @@ -460,30 +473,6 @@ describe('ReviewForm tests', () => { RegStatus.Declared ) - const testComponent = await createTestComponent( - , - { store, history } - ) - store.dispatch( getStorageDeclarationsSuccess( JSON.stringify({ @@ -494,13 +483,40 @@ describe('ReviewForm tests', () => { ) ) store.dispatch(storeDeclaration(declaration)) - testComponent.update() + + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'review', + event: declaration.event.toLowerCase() + }) + ] + } + ) + testComponent.find('#exit-btn').hostNodes().simulate('click') - testComponent.update() - expect(window.location.href).toContain(WORKQUEUE_TABS.readyForReview) + expect(testRouter.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) it('redirect to review tab when exit button is clicked', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + const declaration = createReviewDeclaration( uuid(), birthDraftData, @@ -508,30 +524,6 @@ describe('ReviewForm tests', () => { RegStatus.Validated ) - const testComponent = await createTestComponent( - , - { store, history } - ) - store.dispatch( getStorageDeclarationsSuccess( JSON.stringify({ @@ -542,13 +534,41 @@ describe('ReviewForm tests', () => { ) ) store.dispatch(storeDeclaration(declaration)) - testComponent.update() + + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'review', + event: declaration.event.toLowerCase() + }) + ] + } + ) + testComponent.find('#exit-btn').hostNodes().simulate('click') - testComponent.update() - expect(window.location.href).toContain(WORKQUEUE_TABS.readyForReview) + + expect(testRouter.state.location.pathname).toContain( + WORKQUEUE_TABS.readyForReview + ) }) it('redirect to update tab when exit button is clicked', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + const declaration = createReviewDeclaration( uuid(), birthDraftData, @@ -556,30 +576,6 @@ describe('ReviewForm tests', () => { RegStatus.Rejected ) - const testComponent = await createTestComponent( - , - { store, history } - ) - store.dispatch( getStorageDeclarationsSuccess( JSON.stringify({ @@ -590,43 +586,46 @@ describe('ReviewForm tests', () => { ) ) store.dispatch(storeDeclaration(declaration)) - testComponent.update() + + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'review', + event: declaration.event.toLowerCase() + }) + ] + } + ) + testComponent.find('#exit-btn').hostNodes().simulate('click') - testComponent.update() - expect(window.location.href).toContain(WORKQUEUE_TABS.requiresUpdate) + expect(testRouter.state.location.pathname).toContain( + WORKQUEUE_TABS.requiresUpdate + ) }) it('redirect to progress tab when exit button is clicked', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + const declaration = createReviewDeclaration( uuid(), birthDraftData, EventType.Birth ) - const testComponent = await createTestComponent( - , - { store, history } - ) - store.dispatch( getStorageDeclarationsSuccess( JSON.stringify({ @@ -637,13 +636,39 @@ describe('ReviewForm tests', () => { ) ) store.dispatch(storeDeclaration(declaration)) - testComponent.update() + + const { component: testComponent, router: testRouter } = + await createTestComponent( + , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: declaration.id, + pageId: 'review', + event: declaration.event.toLowerCase() + }) + ] + } + ) + testComponent.find('#exit-btn').hostNodes().simulate('click') - testComponent.update() - expect(window.location.href).toContain('/progress') + + expect(testRouter.state.location.pathname).toContain('/progress') }) it('it checked if review form is already in store and avoid loading from backend', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + const declaration = createReviewDeclaration( uuid(), birthDraftData, @@ -658,32 +683,30 @@ describe('ReviewForm tests', () => { }) ) ) - const testComponent = await createTestComponent( + + store.dispatch(storeDeclaration(declaration)) + + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: declaration.id, pageId: 'review', event: declaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={declaration.id} - />, - { store, history } + }) + ] + } ) - store.dispatch(storeDeclaration(declaration)) - testComponent.update() const data = testComponent .find(RegisterForm) .prop('declaration') as IDeclaration @@ -693,31 +716,33 @@ describe('ReviewForm tests', () => { describe('Death review flow', () => { it('it returns death registration', async () => { - const testComponent = await createTestComponent( + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + + store.dispatch(storeDeclaration(deathDeclaration)) + + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: deathDeclaration.id, pageId: 'review', event: deathDeclaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={deathDeclaration.id} - />, - { store, history } + }) + ] + } ) - store.dispatch(storeDeclaration(deathDeclaration)) testComponent.update() const data = testComponent .find(RegisterForm) @@ -739,32 +764,33 @@ describe('ReviewForm tests', () => { ) }) it('populates proper death event section', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + + store.dispatch(storeDeclaration(deathDeclaration)) const form = await getReviewFormFromStore(store, EventType.Death) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { declarationId: deathDeclaration.id, pageId: 'review', event: deathDeclaration.event.toLowerCase() - }, - isExact: true, - path: '', - url: '' - }} - declarationId={deathDeclaration.id} - />, - { store, history } + }) + ] + } ) - store.dispatch(storeDeclaration(deathDeclaration)) testComponent.update() const data = testComponent .find(RegisterForm) @@ -787,31 +813,31 @@ describe('ReviewForm tests', () => { }) it('shows error message for user with declare scope', async () => { + // NOTE: check auth dispatches actions that eventually will retrieve user data + // from offline storage. Those would override the data we set here. + await flushPromises() + store.dispatch(storeDeclaration(birthDeclaration)) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, { + declarationId: birthDeclaration.id, + pageId: 'review', + event: birthDeclaration.event.toLowerCase() + }) + ] + } ) - testComponent.update() expect( testComponent diff --git a/packages/client/src/views/RegisterForm/ReviewForm.tsx b/packages/client/src/views/RegisterForm/ReviewForm.tsx index 01a88406f27..9f7057e6a9f 100644 --- a/packages/client/src/views/RegisterForm/ReviewForm.tsx +++ b/packages/client/src/views/RegisterForm/ReviewForm.tsx @@ -10,7 +10,10 @@ */ import * as React from 'react' import { Navigate } from 'react-router-dom' -import { RouteComponentProps } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import { WrappedComponentProps as IntlShapeProps, injectIntl } from 'react-intl' import styled, { withTheme } from 'styled-components' import { ITheme } from '@opencrvs/components/lib/theme' @@ -90,6 +93,7 @@ class ReviewFormView extends React.Component { } } } + function getEvent(eventType: string) { switch (eventType && eventType.toLocaleLowerCase()) { case 'birth': @@ -121,6 +125,7 @@ function mapStatetoProps( if (!match?.params?.event) { throw new Error('Event is not provided as path param') } + const reviewFormState: IReviewFormState = getReviewForm( state ) as IReviewFormState @@ -140,6 +145,8 @@ function mapStatetoProps( } } -export const ReviewForm = connect(mapStatetoProps)( - injectIntl(withTheme(ReviewFormView)) +export const ReviewForm = withRouter( + connect(mapStatetoProps)( + injectIntl(withTheme(ReviewFormView)) + ) ) diff --git a/packages/client/src/views/RegisterForm/duplicate/DuplicateForm.test.tsx b/packages/client/src/views/RegisterForm/duplicate/DuplicateForm.test.tsx index 6f5610cc17c..5f6efc611a0 100644 --- a/packages/client/src/views/RegisterForm/duplicate/DuplicateForm.test.tsx +++ b/packages/client/src/views/RegisterForm/duplicate/DuplicateForm.test.tsx @@ -26,7 +26,7 @@ import { ReactWrapper } from 'enzyme' import * as React from 'react' import { Mock, SpyInstance, vi } from 'vitest' -const { store, history } = createStore() +const { store } = createStore() const mockHandler = vi.fn() const draft = createDeclaration(EventType.Birth) @@ -72,7 +72,7 @@ describe('when in device of large viewport', () => { describe('when user is in the review page', () => { let duplicateFormComponent: ReactWrapper<{}, {}> beforeEach(async () => { - const testComponent = await createTestComponent( + const { component } = await createTestComponent( { onChangeReviewForm={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) - duplicateFormComponent = testComponent + duplicateFormComponent = component await waitForElement(duplicateFormComponent, '#review_header') }) diff --git a/packages/client/src/views/RegisterForm/duplicate/DuplicateFormTabs.test.tsx b/packages/client/src/views/RegisterForm/duplicate/DuplicateFormTabs.test.tsx index 14cbd87f53d..05180cfee22 100644 --- a/packages/client/src/views/RegisterForm/duplicate/DuplicateFormTabs.test.tsx +++ b/packages/client/src/views/RegisterForm/duplicate/DuplicateFormTabs.test.tsx @@ -12,7 +12,8 @@ import * as React from 'react' import { createTestComponent, getReviewFormFromStore, - createTestStore + createTestStore, + flushPromises } from '@client/tests/util' import { RegisterForm } from '@client/views/RegisterForm/RegisterForm' import { ReactWrapper } from 'enzyme' @@ -22,11 +23,12 @@ import { setInitialDeclarations } from '@client/declarations' import { v4 as uuid } from 'uuid' -import { REVIEW_EVENT_PARENT_FORM_PAGE } from '@opencrvs/client/src/navigation/routes' +import { REVIEW_EVENT_PARENT_FORM_PAGE_GROUP } from '@opencrvs/client/src/navigation/routes' import { EventType } from '@client/utils/gateway' import * as profileSelectors from '@client/profile/profileSelectors' import { vi } from 'vitest' import { ViewRecordQueries } from '@client/views/ViewRecord/query' +import { formatUrl } from '@client/navigation' const viewRecordMock = { data: { @@ -1141,9 +1143,13 @@ describe('when user is in the register form review section', () => { const mockViewRecordFunction = vi.fn() mockViewRecordFunction.mockReturnValue(viewRecordMock) ViewRecordQueries.fetchDeclarationForViewing = mockViewRecordFunction - let component: ReactWrapper<{}, {}> + + let testComponent: ReactWrapper<{}, {}> + beforeEach(async () => { - const { store, history } = await createTestStore() + const { store } = await createTestStore() + + await flushPromises() const declaration = createReviewDeclaration( uuid(), { @@ -1167,40 +1173,38 @@ describe('when user is in the register form review section', () => { ] store.dispatch(setInitialDeclarations()) store.dispatch(storeDeclaration(declaration)) - const mock: any = vi.fn() + vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['register']) const form = await getReviewFormFromStore(store, EventType.Birth) - const testComponent = await createTestComponent( - // @ts-ignore + const { component } = await createTestComponent( , - { store, history } + { + store, + path: REVIEW_EVENT_PARENT_FORM_PAGE_GROUP, + initialEntries: [ + formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE_GROUP, { + declarationId: declaration.id, + event: EventType.Birth, + groupId: 'review-view-group', + pageId: 'review' + }) + ] + } ) - component = testComponent + + testComponent = component }) it('should show the duplicate tracking id in tab', async () => { expect( - component + testComponent .find('#tab_4090df15-f4e5-4f16-ae7e-bb518129d493') .hostNodes() .text() @@ -1208,13 +1212,13 @@ describe('when user is in the register form review section', () => { }) it('should show comparison when click on duplicate trackingId from tab', async () => { - component + testComponent .find('#tab_4090df15-f4e5-4f16-ae7e-bb518129d493') .hostNodes() .simulate('click') - component.update() + testComponent.update() - expect(component.find('#content-name').hostNodes().text()).toBe( + expect(testComponent.find('#content-name').hostNodes().text()).toBe( 'Is Edgar Samo (BPJM787) a duplicate?' ) }) diff --git a/packages/client/src/views/RegisterForm/review/EditConfirmation.test.tsx b/packages/client/src/views/RegisterForm/review/EditConfirmation.test.tsx index 6fdc726ffff..b0cce6d7a9e 100644 --- a/packages/client/src/views/RegisterForm/review/EditConfirmation.test.tsx +++ b/packages/client/src/views/RegisterForm/review/EditConfirmation.test.tsx @@ -15,20 +15,20 @@ import { createStore } from '@client/store' import { createTestComponent } from '@client/tests/util' import { vi } from 'vitest' -const { store, history } = createStore() +const { store } = createStore() const mockHandleEdit = vi.fn() const mockHandleClose = vi.fn() describe('when user is in the review page', () => { let editComponent: ReactWrapper<{}, {}> beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) editComponent = testComponent }) diff --git a/packages/client/src/views/RegisterForm/review/ReviewSection.test.tsx b/packages/client/src/views/RegisterForm/review/ReviewSection.test.tsx index bc013df11a0..b83268ee1f5 100644 --- a/packages/client/src/views/RegisterForm/review/ReviewSection.test.tsx +++ b/packages/client/src/views/RegisterForm/review/ReviewSection.test.tsx @@ -25,6 +25,7 @@ import { ViewType } from '@client/forms' import { formMessages } from '@client/i18n/messages' +import { formatUrl } from '@client/navigation' import { REVIEW_EVENT_PARENT_FORM_PAGE } from '@client/navigation/routes' import { offlineDataReady } from '@client/offline/actions' import * as profileSelectors from '@client/profile/profileSelectors' @@ -36,6 +37,7 @@ import { mockOfflineData, mockOfflineDataDispatch, resizeWindow, + TestComponentWithRouteMock, userDetails } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' @@ -55,7 +57,7 @@ import { createIntl } from 'react-intl' import { v4 as uuid } from 'uuid' import { Mock, SpyInstance, vi } from 'vitest' -const { store, history } = createStore() +const { store } = createStore() const mockHandler = vi.fn() const draft = createDeclaration(EventType.Birth) @@ -117,9 +119,10 @@ describe('when in device of large viewport', () => { const intl = createIntl({ locale: 'en' }) describe('when user is in the review page', () => { - let reviewSectionComponent: ReactWrapper<{}, {}> + let reviewSectionComponent: TestComponentWithRouteMock['component'] + let reviewSectionRouter: TestComponentWithRouteMock['router'] beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { onChangeReviewForm={mockHandler} userDetails={userDetails} />, - { store, history } + { + store, + initialEntries: [formatUrl(REVIEW_EVENT_PARENT_FORM_PAGE, {})] + } ) reviewSectionComponent = testComponent + reviewSectionRouter = router await waitForElement(reviewSectionComponent, '#review_header') }) @@ -169,7 +176,7 @@ describe('when in device of large viewport', () => { .simulate('click') reviewSectionComponent.update() await flushPromises() - expect(history.location.pathname).toContain('reviews') + expect(reviewSectionRouter.state.location.pathname).toContain('reviews') }) }) @@ -236,7 +243,7 @@ describe('when in device of large viewport', () => { let reviewSectionComponent: ReactWrapper<{}, {}> beforeEach(async () => { vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['register']) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -261,7 +268,7 @@ describe('when in device of large viewport', () => { describe('when user is in the review page for rejected death declaration', () => { let reviewSectionComponent: ReactWrapper<{}, {}> beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -286,7 +293,7 @@ describe('when in device of large viewport', () => { describe('when user is in the review page for rejected marriage declaration', () => { let reviewSectionComponent: ReactWrapper<{}, {}> beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -309,10 +316,12 @@ describe('when in device of large viewport', () => { }) describe('when user is in the review page to validate birth declaration', () => { - let reviewSectionComponent: ReactWrapper<{}, {}> + let reviewSectionComponent: TestComponentWithRouteMock['component'] + let reviewSectionRouter: TestComponentWithRouteMock['router'] + beforeEach(async () => { vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['validator']) - const testComponent = await createTestComponent( + const { component: testComponent, router } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent + reviewSectionRouter = router }) it('Should click the validator Declaration Button', async () => { @@ -363,7 +373,7 @@ describe('when in device of large viewport', () => { .simulate('click') reviewSectionComponent.update() await flushPromises() - expect(history.location.pathname).toContain('reviews') + expect(reviewSectionRouter.state.location.pathname).toContain('reviews') }) }) }) @@ -471,7 +481,7 @@ describe('when in device of large viewport', () => { const simpleDraft = createReviewDeclaration(uuid(), data, EventType.Birth) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -584,7 +594,7 @@ describe('when in device of large viewport', () => { const simpleDraft = createReviewDeclaration(uuid(), data, EventType.Birth) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -734,7 +744,7 @@ describe('when in device of large viewport', () => { const simpleDraft = createReviewDeclaration(uuid(), data, EventType.Birth) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { submitClickEvent={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent }) @@ -888,7 +898,7 @@ describe('when in device of small viewport', () => { DeclarationEvent.Birth ) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { onChangeReviewForm={mockHandler} userDetails={userDetails} />, - { store, history } + { store } ) reviewSectionComponent = testComponent diff --git a/packages/client/src/views/RegisterForm/review/ReviewSection.tsx b/packages/client/src/views/RegisterForm/review/ReviewSection.tsx index 1bb6a5f881c..7db662cfe33 100644 --- a/packages/client/src/views/RegisterForm/review/ReviewSection.tsx +++ b/packages/client/src/views/RegisterForm/review/ReviewSection.tsx @@ -135,7 +135,10 @@ import { DuplicateForm } from '@client/views/RegisterForm/duplicate/DuplicateFor import { Button } from '@opencrvs/components/lib/Button' import { UserDetails } from '@client/utils/userUtils' import { FormFieldGenerator } from '@client/components/form' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' const Deleted = styled.del` color: ${({ theme }) => theme.colors.negative}; diff --git a/packages/client/src/views/RegisterForm/review/ReviewSectionCorrection.tsx b/packages/client/src/views/RegisterForm/review/ReviewSectionCorrection.tsx index 4398d5be525..7a34833d522 100644 --- a/packages/client/src/views/RegisterForm/review/ReviewSectionCorrection.tsx +++ b/packages/client/src/views/RegisterForm/review/ReviewSectionCorrection.tsx @@ -33,7 +33,10 @@ import { IStoreState } from '@client/store' import { UserDetails } from '@client/utils/userUtils' import { getUserDetails } from '@client/profile/profileSelectors' import { generateGoToHomeTabUrl } from '@client/navigation' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' interface IChildrenProps { toggleRejectModal: () => void diff --git a/packages/client/src/views/SearchResult/AdvancedSearch.test.tsx b/packages/client/src/views/SearchResult/AdvancedSearch.test.tsx index 1bf29010ba8..c406ea990c4 100644 --- a/packages/client/src/views/SearchResult/AdvancedSearch.test.tsx +++ b/packages/client/src/views/SearchResult/AdvancedSearch.test.tsx @@ -8,30 +8,21 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import * as React from 'react' +import { ADVANCED_SEARCH_RESULT } from '@client/navigation/routes' +import { setAdvancedSearchParam } from '@client/search/advancedSearch/actions' +import { createStore } from '@client/store' +import { createTestComponent } from '@client/tests/util' import { ReactWrapper } from 'enzyme' -import { createRouterProps, createTestComponent } from '@client/tests/util' +import * as React from 'react' +import { createMemoryRouter } from 'react-router-dom' import { AdvancedSearchConfig } from './AdvancedSearch' -import { createStore } from '@client/store' -import { setAdvancedSearchParam } from '@client/search/advancedSearch/actions' -import { formatUrl } from '@client/navigation' -import { - ADVANCED_SEARCH, - ADVANCED_SEARCH_RESULT -} from '@client/navigation/routes' let testComponent: ReactWrapper beforeEach(async () => { - const { store, history } = createStore() - testComponent = await createTestComponent( - // @ts-ignore - , - { store, history } - ) + const { store } = createStore() + testComponent = ( + await createTestComponent(, { store }) + )?.component testComponent.update() }) @@ -57,8 +48,9 @@ describe('when advancedSearchPage renders with no active params in store', () => describe('when advancedSearchPage renders with 2 or more active params in store', () => { let testComponent: ReactWrapper + let router: ReturnType beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.dispatch( setAdvancedSearchParam({ event: 'birth', @@ -66,10 +58,12 @@ describe('when advancedSearchPage renders with 2 or more active params in store' registrationStatuses: ['IN_PROGRESS'] }) ) - testComponent = await createTestComponent( + ;({ component: testComponent, router } = await createTestComponent( , - { store, history } - ) + { + store + } + )) testComponent.update() }) @@ -87,6 +81,8 @@ describe('when advancedSearchPage renders with 2 or more active params in store' it('goes to advancedSearch Result page if search button is clicked', async () => { testComponent.find('#search').hostNodes().simulate('click') - expect(window.location.href).toContain(`${ADVANCED_SEARCH_RESULT}`) + expect(router.state.location.pathname).toContain( + `${ADVANCED_SEARCH_RESULT}` + ) }) }) diff --git a/packages/client/src/views/SearchResult/SearchResult.test.tsx b/packages/client/src/views/SearchResult/SearchResult.test.tsx index 56e24fd540d..2f99949f936 100644 --- a/packages/client/src/views/SearchResult/SearchResult.test.tsx +++ b/packages/client/src/views/SearchResult/SearchResult.test.tsx @@ -18,7 +18,7 @@ import { SEARCH_EVENTS } from '@client/search/queries' import { createStore } from '@client/store' import { createTestComponent, mockUserResponse } from '@client/tests/util' import { SearchResult } from '@client/views/SearchResult/SearchResult' -import { goToSearch } from '@client/navigation' + import { waitForElement } from '@client/tests/wait-for-element' import { EventType } from '@client/utils/gateway' import { storeDeclaration } from '@client/declarations' @@ -52,22 +52,22 @@ queries.fetchUserDetails = mockFetchUserDetails describe('SearchResult tests', () => { let store: ReturnType['store'] - let history: ReturnType['history'] + beforeEach(async () => { - ;({ store, history } = createStore()) + ;({ store } = createStore()) getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) }) it('sets loading state while waiting for data', async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store, initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] } ) // @ts-ignore @@ -296,14 +296,18 @@ describe('SearchResult tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=01622688232&searchType=PHONE_NUMBER'] + } ) // wait for mocked data to load mockedProvider @@ -336,14 +340,18 @@ describe('SearchResult tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=+8801622688232&searchType=PHONE_NUMBER'] + } ) // wait for mocked data to load mockedProvider @@ -359,8 +367,8 @@ describe('SearchResult tests', () => { it('renders empty search page with a header in small devices', async () => { const testSearchResultComponent = await createTestComponent( //@ts-ignore - , - { store, history } + , + { store, initialEntries: ['/search?location='] } ) Object.defineProperty(window, 'innerWidth', { @@ -368,9 +376,9 @@ describe('SearchResult tests', () => { configurable: true, value: 200 }) - store.dispatch(goToSearch()) + // store.dispatch(goToSearch()) - const searchTextInput = testSearchResultComponent + const searchTextInput = testSearchResultComponent.component .find('#searchText') .hostNodes() @@ -378,12 +386,12 @@ describe('SearchResult tests', () => { searchTextInput.simulate('change', { target: { value: 'DW0UTHR' } }) - testSearchResultComponent + testSearchResultComponent.component .find('#searchIconButton') .hostNodes() .simulate('click') - expect(window.location.search).toBe( + expect(testSearchResultComponent.router.state.location.search).toBe( '?searchText=DW0UTHR&searchType=TRACKING_ID' ) }) @@ -451,14 +459,18 @@ describe('SearchResult tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] + } ) // wait for mocked data to load mockedProvider @@ -550,14 +562,13 @@ describe('SearchResult tests', () => { configurable: true, value: 1100 }) - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMock as any } + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] + } ) // wait for mocked data to load mockedProvider @@ -647,14 +658,18 @@ describe('SearchResult tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] + } ) // wait for mocked data to load mockedProvider @@ -675,9 +690,9 @@ describe('SearchResult tests', () => { describe('SearchResult downloadButton tests', () => { let store: ReturnType['store'] - let history: ReturnType['history'] + beforeEach(async () => { - ;({ store, history } = createStore()) + ;({ store } = createStore()) getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) }) @@ -754,14 +769,18 @@ describe('SearchResult downloadButton tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] + } ) // wait for mocked data to load mockedProvider @@ -851,14 +870,18 @@ describe('SearchResult downloadButton tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: graphqlMock as any } + { + store, + graphqlMocks: graphqlMock as any, + initialEntries: ['/?searchText=DW0UTHR&searchType=TRACKING_ID'] + } ) // wait for mocked data to load mockedProvider diff --git a/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.test.tsx b/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.test.tsx index 99ea2a039bb..e6905c75529 100644 --- a/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.test.tsx +++ b/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.test.tsx @@ -8,26 +8,27 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import { createTestApp, flushPromises, waitForReady } from '@client/tests/util' import { SELECT_VITAL_EVENT } from '@client/navigation/routes' -import { ReactWrapper } from 'enzyme' -import { History } from 'history' +import { createTestApp, flushPromises, waitForReady } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' +import { ReactWrapper } from 'enzyme' +import { createMemoryRouter } from 'react-router-dom' describe('when user is selecting the vital event', () => { let app: ReactWrapper - let history: History + let router: ReturnType beforeEach(async () => { const testApp = await createTestApp() app = testApp.app - history = testApp.history + router = testApp.router + await waitForReady(app) }) describe('when user is in vital event selection view', () => { beforeEach(async () => { - history.replace(SELECT_VITAL_EVENT) + router.navigate(SELECT_VITAL_EVENT, { replace: true }) await waitForElement(app, '#select_vital_event_view') }) it('lists the options', () => { @@ -51,8 +52,8 @@ describe('when user is selecting the vital event', () => { app.find('#select_death_event').hostNodes().simulate('change') app.find('#continue').hostNodes().simulate('click') }) - it('takses user to the death registration form', () => { - expect(history.location.pathname).toContain('events/death') + it('takes user to the death registration form', () => { + expect(router.state.location.pathname).toContain('events/death') }) }) diff --git a/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.tsx b/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.tsx index 62b20476336..782204660ab 100644 --- a/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.tsx +++ b/packages/client/src/views/SelectVitalEvent/SelectVitalEvent.tsx @@ -29,7 +29,10 @@ import { createDeclaration } from '@client/declarations' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' type DispatchProps = { diff --git a/packages/client/src/views/Settings/ChangeEmailModal/ChangeEmailModal.test.tsx b/packages/client/src/views/Settings/ChangeEmailModal/ChangeEmailModal.test.tsx index 735195b2d42..44b8728dab3 100644 --- a/packages/client/src/views/Settings/ChangeEmailModal/ChangeEmailModal.test.tsx +++ b/packages/client/src/views/Settings/ChangeEmailModal/ChangeEmailModal.test.tsx @@ -59,7 +59,7 @@ describe('Change email modal tests', () => { beforeEach(async () => { store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { />, { store, - history, graphqlMocks } ) diff --git a/packages/client/src/views/Settings/ChangePhoneModal/ChangePhoneModal.test.tsx b/packages/client/src/views/Settings/ChangePhoneModal/ChangePhoneModal.test.tsx index ddd8540a03c..12e3f5de5a8 100644 --- a/packages/client/src/views/Settings/ChangePhoneModal/ChangePhoneModal.test.tsx +++ b/packages/client/src/views/Settings/ChangePhoneModal/ChangePhoneModal.test.tsx @@ -59,7 +59,7 @@ describe('Change phone modal tests', () => { beforeEach(async () => { store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( { />, { store, - history, graphqlMocks } ) diff --git a/packages/client/src/views/Settings/Settings.test.tsx b/packages/client/src/views/Settings/Settings.test.tsx index c490eccde20..8223d0465a0 100644 --- a/packages/client/src/views/Settings/Settings.test.tsx +++ b/packages/client/src/views/Settings/Settings.test.tsx @@ -63,15 +63,15 @@ const graphqlMocks = [ ] describe('Settings page tests', () => { - const { store, history } = createStore() + const { store } = createStore() let component: ReactWrapper beforeEach(async () => { store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore , - { store, history, graphqlMocks } + { store, graphqlMocks } ) component = testComponent }) diff --git a/packages/client/src/views/SysAdmin/Config/Systems/Systems.test.tsx b/packages/client/src/views/SysAdmin/Config/Systems/Systems.test.tsx index 1ed0956f920..b78779b8818 100644 --- a/packages/client/src/views/SysAdmin/Config/Systems/Systems.test.tsx +++ b/packages/client/src/views/SysAdmin/Config/Systems/Systems.test.tsx @@ -19,8 +19,8 @@ import { selectOption } from '@client/tests/util' import { SystemList } from '@client/views/SysAdmin/Config/Systems/Systems' -import { useParams } from 'react-router-dom' -import { describe, Mock } from 'vitest' + +import { describe } from 'vitest' import { activateSystem, deactivateSystem, @@ -34,13 +34,15 @@ describe('render system integration', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() - component = await createTestComponent(, { - store, - history - }) - ;(useParams as Mock).mockImplementation(() => ({})) + const { component: testComponent } = await createTestComponent( + , + { + store + } + ) + component = testComponent }) it('Render system integrations properly ', async () => { @@ -78,13 +80,16 @@ describe('render create system integrations', () => { ] beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() - component = await createTestComponent(, { - store, - history, - graphqlMocks: mocks - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: mocks + } + ) + component = testComponent }) it('should show the system creation modal after click the create button', async () => { @@ -164,13 +169,16 @@ describe('render create webhook system integrations', () => { ] beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() - component = await createTestComponent(, { - store, - history, - graphqlMocks: mocks - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: mocks + } + ) + component = testComponent }) it('should show the system creation modal after click the create button', async () => { @@ -234,7 +242,7 @@ describe('render toggle settings', () => { describe('delete system integration', () => { beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() @@ -258,11 +266,14 @@ describe('render toggle settings', () => { } ] - component = await createTestComponent(, { - store, - history, - graphqlMocks: mocks - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: mocks + } + ) + component = testComponent }) it('should delete system successfully', async () => { @@ -288,7 +299,7 @@ describe('render toggle settings', () => { describe('deactivate system integration', () => { beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() @@ -312,11 +323,14 @@ describe('render toggle settings', () => { } ] - component = await createTestComponent(, { - store, - history, - graphqlMocks: mocks - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: mocks + } + ) + component = testComponent }) it('should deactivated system successfully', async () => { @@ -344,7 +358,7 @@ describe('render toggle settings', () => { describe('active system integration', () => { beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() @@ -367,11 +381,14 @@ describe('render toggle settings', () => { } ] - component = await createTestComponent(, { - store, - history, - graphqlMocks: mocks - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: mocks + } + ) + component = testComponent }) it('should active system successfully', async () => { diff --git a/packages/client/src/views/SysAdmin/Performance/CompletenessRates.test.tsx b/packages/client/src/views/SysAdmin/Performance/CompletenessRates.test.tsx index 989630c1c97..ab773f3aa34 100644 --- a/packages/client/src/views/SysAdmin/Performance/CompletenessRates.test.tsx +++ b/packages/client/src/views/SysAdmin/Performance/CompletenessRates.test.tsx @@ -11,8 +11,12 @@ import * as React from 'react' import { ReactWrapper } from 'enzyme' -import { History } from 'history' -import { createTestComponent, createTestStore } from '@client/tests/util' + +import { + createTestComponent, + createTestStore, + TestComponentWithRouteMock +} from '@client/tests/util' import { AppStore } from '@client/store' import { CompletenessRates } from '@client/views/SysAdmin/Performance/CompletenessRates' import { EVENT_COMPLETENESS_RATES } from '@client/navigation/routes' @@ -24,6 +28,7 @@ import { waitForElement } from '@client/tests/wait-for-element' import { stringify, parse } from 'query-string' import { GraphQLError } from 'graphql' import { vi } from 'vitest' +import { formatUrl } from '@client/navigation' const LOCATION_DHAKA_DIVISION = { displayLabel: 'Dhaka Division', @@ -91,37 +96,37 @@ describe('Registraion Rates tests', () => { } ] let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] let store: AppStore - let history: History beforeAll(async () => { Date.now = vi.fn(() => 1487076708000) - const { store: testStore, history: testHistory } = await createTestStore() + const { store: testStore } = await createTestStore() store = testStore - history = testHistory }) beforeEach(async () => { - component = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMocks } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: EVENT_COMPLETENESS_RATES, + initialEntries: [ + formatUrl(EVENT_COMPLETENESS_RATES, { + eventType: 'birth' + }) + + '?' + + stringify({ + time: 'withinTarget', + locationId: LOCATION_DHAKA_DIVISION.id, + timeEnd: new Date(1487076708000).toISOString(), + timeStart: new Date(1456868800000).toISOString() + }) + ], + graphqlMocks: graphqlMocks + }) + + component = testComponent + router = testRouter // wait for mocked data to load mockedProvider await new Promise((resolve) => { @@ -146,7 +151,7 @@ describe('Registraion Rates tests', () => { '#date-range-picker-action' ) expect(dateRangePickerElement.hostNodes().text()).toBe('Last 12 months') - const previousQueryParams = history.location.search + const previousQueryParams = router.state.location.search dateRangePickerElement.hostNodes().simulate('click') const last30DaysPresetButtonElement = await waitForElement( component, @@ -158,7 +163,7 @@ describe('Registraion Rates tests', () => { '#date-range-confirm-action' ) confirmButtonElement.hostNodes().simulate('click') - expect(history.location.search).not.toBe(previousQueryParams) + expect(router.state.location.search).not.toBe(previousQueryParams) }) it('click on close button or outside modal closes location picker modal', async () => { @@ -181,7 +186,10 @@ describe('Registraion Rates tests', () => { }) it('changing location id from location picker updates the query params', async () => { - const locationIdBeforeChange = parse(history.location.search).locationId + const locationIdBeforeChange = parse( + router.state.location.search + ).locationId + const locationPickerElement = await waitForElement( component, '#location-range-picker-action' @@ -202,7 +210,8 @@ describe('Registraion Rates tests', () => { '#locationOptionbfe8306c-0910-48fe-8bf5-0db906cf3155' ) searchResultOption.hostNodes().simulate('click') - const newLocationId = parse(history.location.search).locationId + + const newLocationId = parse(router.state.location.search).locationId expect(newLocationId).not.toBe(locationIdBeforeChange) expect(newLocationId).toBe('bfe8306c-0910-48fe-8bf5-0db906cf3155') }) @@ -238,33 +247,32 @@ describe('Registraion Rates error state tests', () => { ] let component: ReactWrapper<{}, {}> let store: AppStore - let history: History beforeEach(async () => { Date.now = vi.fn(() => 1487076708000) - ;({ store, history } = await createTestStore()) + ;({ store } = await createTestStore()) - component = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMocks } + const { component: testComponent } = await createTestComponent( + , + { + store, + path: EVENT_COMPLETENESS_RATES, + initialEntries: [ + formatUrl(EVENT_COMPLETENESS_RATES, { + eventType: 'birth' + }) + + '?' + + stringify({ + time: 'withinTarget', + locationId: LOCATION_DHAKA_DIVISION.id, + timeEnd: new Date(1487076708000).toISOString(), + timeStart: new Date(1455454308000).toISOString() + }) + ], + graphqlMocks: graphqlMocks + } ) - + component = testComponent // wait for mocked data to load mockedProvider await new Promise((resolve) => { setTimeout(resolve, 100) diff --git a/packages/client/src/views/SysAdmin/Performance/PerformanceHome.test.tsx b/packages/client/src/views/SysAdmin/Performance/PerformanceHome.test.tsx index e24d9b9de0b..60db36d02bb 100644 --- a/packages/client/src/views/SysAdmin/Performance/PerformanceHome.test.tsx +++ b/packages/client/src/views/SysAdmin/Performance/PerformanceHome.test.tsx @@ -33,7 +33,7 @@ const graphqlMocks: MockedProvider['props']['mocks'] = [ describe('Performance home test', () => { describe('Performance home without location in props', () => { - const { store, history } = createStore() + const { store } = createStore() let app: ReactWrapper beforeAll(async () => { @@ -42,23 +42,21 @@ describe('Performance home test', () => { id: '6e1f3bce-7bcb-4bf6-8e35-0d9facdf158b', searchableText: 'Dhaka' } - app = await createTestComponent( - , - { - store, - history, - graphqlMocks + + const { location } = createRouterProps('/performance', undefined, { + search: { + locationId: LOCATION_DHAKA_DIVISION.id, + event: EventType.Birth, + timeEnd: new Date(1487076708000).toISOString(), + timeStart: new Date(1455454308000).toISOString() } - ) + }) + + ;({ component: app } = await createTestComponent(, { + store, + graphqlMocks, + initialEntries: [location.pathname + '?' + location.search] + })) // wait for mocked data to load mockedProvider await new Promise((resolve) => { setTimeout(resolve, 100) diff --git a/packages/client/src/views/SysAdmin/Performance/WorkflowStatus.test.tsx b/packages/client/src/views/SysAdmin/Performance/WorkflowStatus.test.tsx index f1667f5eb72..2f6927af5b6 100644 --- a/packages/client/src/views/SysAdmin/Performance/WorkflowStatus.test.tsx +++ b/packages/client/src/views/SysAdmin/Performance/WorkflowStatus.test.tsx @@ -8,35 +8,33 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ +import { formatUrl } from '@client/navigation' +import { WORKFLOW_STATUS } from '@client/navigation/routes' import { AppStore } from '@client/store' -import { createTestComponent, createTestStore } from '@client/tests/util' +import { + createTestComponent, + createTestStore, + TestComponentWithRouteMock +} from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' import { EventType } from '@client/utils/gateway' -import { - IHistoryStateProps, - WorkflowStatus -} from '@client/views/SysAdmin/Performance/WorkflowStatus' +import { WorkflowStatus } from '@client/views/SysAdmin/Performance/WorkflowStatus' import { ReactWrapper } from 'enzyme' import { GraphQLError } from 'graphql' -import { createBrowserHistory, createLocation, History } from 'history' import { parse, stringify } from 'query-string' import * as React from 'react' -import { match } from 'react-router-dom' import { vi } from 'vitest' import { FETCH_EVENTS_WITH_PROGRESS } from './queries' describe('Workflow status tests', () => { let store: AppStore - let history: History let component: ReactWrapper<{}, {}> - const timeStart = new Date(2019, 11, 6) - const timeEnd = new Date(2019, 11, 13) + let router: TestComponentWithRouteMock['router'] const locationId = 'bfe8306c-0910-48fe-8bf5-0db906cf3155' beforeAll(async () => { const testStore = await createTestStore() store = testStore.store - history = testStore.history Date.now = vi.fn(() => 1590220497869) }) @@ -229,30 +227,25 @@ describe('Workflow status tests', () => { ] beforeEach(async () => { - const path = '/performance/operations/workflowStatus' - const location = createLocation(path, { - timeStart, - timeEnd - }) - const history = createBrowserHistory() - history.location = location - location.search = stringify({ - locationId, - event: 'BIRTH', - status: 'REGISTERED' - }) - const match: match = { - isExact: false, - path, - url: path, - params: {} - } - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + graphqlMocks, + path: WORKFLOW_STATUS, + initialEntries: [ + '/', + formatUrl(WORKFLOW_STATUS, {}) + + '?' + + stringify({ + locationId, + event: 'BIRTH', + status: 'REGISTERED' + }) + ] + }) component = testComponent + router = testRouter component.update() await waitForElement(component, '#declaration-status-list') @@ -264,7 +257,7 @@ describe('Workflow status tests', () => { '#header-go-back-button' ) backButton.hostNodes().simulate('click') - expect(history.location.pathname).toBe('/') + expect(router.state.location.pathname).toBe('/') }) it('renders data', async () => { @@ -307,7 +300,7 @@ describe('Workflow status tests', () => { const eventSelect = await waitForElement(component, '#event-select') eventSelect.at(0).prop('onChange')({ label: 'Deaths', value: 'DEATH' }) component.update() - expect(parse(history.location.search).event).toBe('DEATH') + expect(parse(router.state.location.search).event).toBe('DEATH') }) it('update status from select updates query params', async () => { @@ -317,7 +310,7 @@ describe('Workflow status tests', () => { value: 'REGISTERED' }) component.update() - expect(parse(history.location.search).status).toBe('REGISTERED') + expect(parse(router.state.location.search).status).toBe('REGISTERED') }) }) @@ -341,27 +334,22 @@ describe('Workflow status tests', () => { ] beforeEach(async () => { - const path = '/performance/operations/workflowStatus' - const location = createLocation(path, { - timeStart, - timeEnd - }) - const history = createBrowserHistory() - history.location = location - location.search = stringify({ - locationId, - event: 'BIRTH', - status: 'REGISTERED' - }) - const match: match = { - isExact: false, - path, - url: path, - params: {} - } - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks: graphqlMocksWithError } + const { component: testComponent } = await createTestComponent( + , + { + store, + path: WORKFLOW_STATUS, + initialEntries: [ + formatUrl(WORKFLOW_STATUS, {}) + + '?' + + stringify({ + locationId, + event: 'BIRTH', + status: 'REGISTERED' + }) + ], + graphqlMocks: graphqlMocksWithError + } ) component = testComponent diff --git a/packages/client/src/views/SysAdmin/Performance/reports/completenessRates/CompletenessDataTable.test.tsx b/packages/client/src/views/SysAdmin/Performance/reports/completenessRates/CompletenessDataTable.test.tsx index a913392e1e4..21f4ca40b74 100644 --- a/packages/client/src/views/SysAdmin/Performance/reports/completenessRates/CompletenessDataTable.test.tsx +++ b/packages/client/src/views/SysAdmin/Performance/reports/completenessRates/CompletenessDataTable.test.tsx @@ -16,15 +16,12 @@ import { createTestComponent } from '@client/tests/util' import { CompletenessDataTable } from '@client/views/SysAdmin/Performance/reports/completenessRates/CompletenessDataTable' import { EventType } from '@client/utils/gateway' import { waitForElement } from '@client/tests/wait-for-element' - -import { History } from 'history' import { COMPLETENESS_RATE_REPORT_BASE } from '@client/views/SysAdmin/Performance/CompletenessRates' import { CompletenessRateTime } from '@client/views/SysAdmin/Performance/utils' describe('CompletenessDataTable tests for over time option', () => { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History const mockData = [ { @@ -48,11 +45,11 @@ describe('CompletenessDataTable tests for over time option', () => { ] beforeAll(async () => { - ;({ history, store } = createStore()) + ;({ store } = createStore()) }) beforeEach(async () => { - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { eventType={EventType.Birth} data={mockData} />, - { store, history } + { store } ) + component = testComponent }) it('runs without crashing', async () => { @@ -86,7 +84,6 @@ describe('CompletenessDataTable tests for over time option', () => { describe('CompletenessDataTable tests for by location option', () => { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History const mockData = [ { @@ -112,11 +109,11 @@ describe('CompletenessDataTable tests for by location option', () => { ] beforeAll(async () => { - ;({ history, store } = createStore()) + ;({ store } = createStore()) }) beforeEach(async () => { - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { eventType={EventType.Birth} data={mockData} />, - { store, history } + { store } ) + component = testComponent }) it('runs without crashing', async () => { diff --git a/packages/client/src/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView.test.tsx b/packages/client/src/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView.test.tsx index e4d57472cfc..61d731d6f88 100644 --- a/packages/client/src/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView.test.tsx +++ b/packages/client/src/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView.test.tsx @@ -8,6 +8,9 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ +import { offlineDataReady } from '@client/offline/actions' +import { queries } from '@client/profile/queries' +import { AppStore } from '@client/store' import { createTestComponent, createTestStore, @@ -15,21 +18,17 @@ import { mockOfflineDataDispatch, mockRegistrarUserResponse } from '@client/tests/util' -import { queries } from '@client/profile/queries' -import { checkAuth } from '@opencrvs/client/src/profile/profileActions' -import { StatusWiseDeclarationCountView } from '@client/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView' -import { AppStore } from '@client/store' -import * as React from 'react' +import { waitForElement } from '@client/tests/wait-for-element' +import { EventType } from '@client/utils/gateway' import type { GQLRegistrationCountResult } from '@client/utils/gateway-deprecated-do-not-use' -import { ReactWrapper } from 'enzyme' import * as locationUtils from '@client/utils/locationUtils' +import { StatusWiseDeclarationCountView } from '@client/views/SysAdmin/Performance/reports/operational/StatusWiseDeclarationCountView' import * as performanceUtils from '@client/views/SysAdmin/Performance/utils' -import { waitForElement } from '@client/tests/wait-for-element' import { StatusMapping } from '@client/views/SysAdmin/Performance/WorkflowStatus' -import { EventType } from '@client/utils/gateway' -import { History } from 'history' -import { offlineDataReady } from '@client/offline/actions' -import { vi, Mock } from 'vitest' +import { checkAuth } from '@opencrvs/client/src/profile/profileActions' +import { ReactWrapper } from 'enzyme' +import * as React from 'react' +import { Mock, vi } from 'vitest' const registerScopeToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWdpc3RlciIsImNlcnRpZnkiLCJkZW1vIl0sImlhdCI6MTU0MjY4ODc3MCwiZXhwIjoxNTQzMjkzNTcwLCJhdWQiOlsib3BlbmNydnM6YXV0aC11c2VyIiwib3BlbmNydnM6dXNlci1tZ250LXVzZXIiLCJvcGVuY3J2czpoZWFydGgtdXNlciIsIm9wZW5jcnZzOmdhdGV3YXktdXNlciIsIm9wZW5jcnZzOm5vdGlmaWNhdGlvbi11c2VyIiwib3BlbmNydnM6d29ya2Zsb3ctdXNlciJdLCJpc3MiOiJvcGVuY3J2czphdXRoLXNlcnZpY2UiLCJzdWIiOiI1YmVhYWY2MDg0ZmRjNDc5MTA3ZjI5OGMifQ.ElQd99Lu7WFX3L_0RecU_Q7-WZClztdNpepo7deNHqzro-Cog4WLN7RW3ZS5PuQtMaiOq1tCb-Fm3h7t4l4KDJgvC11OyT7jD6R2s2OleoRVm3Mcw5LPYuUVHt64lR_moex0x_bCqS72iZmjrjS-fNlnWK5zHfYAjF2PWKceMTGk6wnI9N49f6VwwkinJcwJi6ylsjVkylNbutQZO0qTc7HRP-cBfAzNcKD37FqTRNpVSvHdzQSNcs7oiv3kInDN5aNa2536XSd3H-RiKR9hm9eID9bSIJgFIGzkWRd5jnoYxT70G0t03_mTVnDnqPXDtyI-lmerx24Ost0rQLUNIg' @@ -42,11 +41,11 @@ queries.fetchUserDetails = mockFetchUserDetails describe('Status wise registration count', () => { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History + beforeEach(async () => { const storeContext = await createTestStore() store = storeContext.store - history = storeContext.history + getItem.mockReturnValue(registerScopeToken) await store.dispatch(checkAuth()) store.dispatch(offlineDataReady(mockOfflineDataDispatch)) @@ -71,7 +70,7 @@ describe('Status wise registration count', () => { ], total: 15 } - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( { statusMapping={StatusMapping} onClickStatusDetails={onClickStatusDetailsMock} />, - { store, history } + { store } ) + component = testComponent }) it('renders status count view with progress bars', async () => { expect(component.find('#declaration-statuses').hostNodes()).toHaveLength( diff --git a/packages/client/src/views/SysAdmin/SysAdminContentWrapper.test.tsx b/packages/client/src/views/SysAdmin/SysAdminContentWrapper.test.tsx index 21cdff93ff2..d7edb6ba28a 100644 --- a/packages/client/src/views/SysAdmin/SysAdminContentWrapper.test.tsx +++ b/packages/client/src/views/SysAdmin/SysAdminContentWrapper.test.tsx @@ -18,20 +18,20 @@ import { } from './SysAdminContentWrapper' describe('Performance content wrapper', () => { - const { store, history } = createStore() + const { store } = createStore() describe('Tab menu', () => { let app: ReactWrapper beforeAll(async () => { - app = await createTestComponent( + ;({ component: app } = await createTestComponent( {}} />, - { store, history } - ) + { store } + )) app.update() }) diff --git a/packages/client/src/views/SysAdmin/Team/TeamSearch.test.tsx b/packages/client/src/views/SysAdmin/Team/TeamSearch.test.tsx index 4ad1db0e781..95df52e1c60 100644 --- a/packages/client/src/views/SysAdmin/Team/TeamSearch.test.tsx +++ b/packages/client/src/views/SysAdmin/Team/TeamSearch.test.tsx @@ -10,44 +10,41 @@ */ import { TEAM_SEARCH } from '@client/navigation/routes' +import { checkAuth } from '@client/profile/profileActions' +import { queries } from '@client/profile/queries' import { AppStore } from '@client/store' import { - createTestApp, createTestComponent, createTestStore, flushPromises, mockUserResponse, registerScopeToken } from '@client/tests/util' +import { waitForElement } from '@client/tests/wait-for-element' import { ReactWrapper } from 'enzyme' -import { History } from 'history' +import { merge } from 'lodash' import { parse } from 'query-string' import * as React from 'react' -import { TeamSearch } from './TeamSearch' -import { waitForElement } from '@client/tests/wait-for-element' -import { checkAuth } from '@client/profile/profileActions' +import { createMemoryRouter } from 'react-router-dom' import { Mock, vi } from 'vitest' -import { merge } from 'lodash' -import { queries } from '@client/profile/queries' +import { TeamSearch } from './TeamSearch' describe('Team search test', () => { let store: AppStore - let history: History + let router: ReturnType beforeAll(async () => { - const { store: testStore, history: testHistory } = await createTestStore() + const { store: testStore } = await createTestStore() store = testStore - history = testHistory }) describe('Team search without location in props', () => { let app: ReactWrapper beforeAll(async () => { - app = await createTestComponent(, { - store, - history - }) + ;({ component: app, router } = await createTestComponent(, { + store + })) app.update() }) @@ -84,16 +81,15 @@ describe('Team search test', () => { app.update() flushPromises() - expect(parse(history.location.search)).toEqual({ + expect(parse(router.state.location.search)).toEqual({ locationId: '0d8474da-0361-4d32-979e-af91f012340a' }) - expect(history.location.pathname).toContain('/team/users') + expect(router.state.location.pathname).toContain('/team/users') }) }) describe('Team search with location in props', () => { - let app: ReactWrapper - let history: History + let testComponent: ReactWrapper<{}, {}> const getItem = window.localStorage.getItem as Mock const mockFetchUserDetails = vi.fn() const nameObj = { @@ -126,9 +122,6 @@ describe('Team search test', () => { } } - // storage.getItem = vi.fn() - // storage.setItem = vi.fn() - beforeAll(async () => { merge(mockUserResponse, nameObj) mockFetchUserDetails.mockReturnValue(mockUserResponse) @@ -141,23 +134,29 @@ describe('Team search test', () => { }) beforeEach(async () => { - const testApp = await createTestApp() - app = testApp.app - history = testApp.history - - history.replace(TEAM_SEARCH, { - selectedLocation: { - id: '', - searchableText: '', - displayLabel: 'Alokbali Union Parishad' - } - }) + testComponent = ( + await createTestComponent(, { + store, + initialEntries: [ + { + pathname: TEAM_SEARCH, + state: { + selectedLocation: { + id: '', + searchableText: '', + displayLabel: 'Alokbali Union Parishad' + } + } + } + ] + }) + )?.component }) it('loads the location in the search input box', async () => { - await waitForElement(app, '#locationSearchInput') + await waitForElement(testComponent, '#locationSearchInput') expect( - app.find('#locationSearchInput').hostNodes().props().value + testComponent.find('#locationSearchInput').hostNodes().props().value ).toEqual('Alokbali Union Parishad') }) }) diff --git a/packages/client/src/views/SysAdmin/Team/TeamSearch.tsx b/packages/client/src/views/SysAdmin/Team/TeamSearch.tsx index 3b8cbb97c7d..ccfabb00dd5 100644 --- a/packages/client/src/views/SysAdmin/Team/TeamSearch.tsx +++ b/packages/client/src/views/SysAdmin/Team/TeamSearch.tsx @@ -28,7 +28,10 @@ import { NoWifi } from '@opencrvs/components/lib/icons' import { withOnlineStatus } from '@client/views/OfficeHome/LoadingIndicator' import { constantsMessages } from '@client/i18n/messages/constants' import { buttonMessages } from '@client/i18n/messages/buttons' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' import { stringify } from 'query-string' @@ -66,7 +69,7 @@ const Text = styled.div` class TeamSearchComponent extends React.Component { constructor(props: Props) { super(props) - const historyState = props.router.location.state // @TODO: Check if this is true + const historyState = props.router.location.state this.state = { selectedLocation: (historyState && historyState?.selectedLocation) || undefined diff --git a/packages/client/src/views/SysAdmin/Team/user/UserAuditActionModal.test.tsx b/packages/client/src/views/SysAdmin/Team/user/UserAuditActionModal.test.tsx index 424bf547f46..24ff7cdeae2 100644 --- a/packages/client/src/views/SysAdmin/Team/user/UserAuditActionModal.test.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/UserAuditActionModal.test.tsx @@ -16,7 +16,6 @@ import { AppStore, createStore } from '@client/store' import { waitFor, waitForElement } from '@client/tests/wait-for-element' import { USER_AUDIT_ACTION } from '@client/user/queries' import { GraphQLError } from 'graphql' -import { History } from 'history' import { vi, Mock } from 'vitest' import { SystemRoleType, Status } from '@client/utils/gateway' import { UserDetails } from '@client/utils/userUtils' @@ -179,11 +178,10 @@ const graphqlMocksOfReactivate = [ describe('user audit action modal tests', () => { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History let onCloseMock: Mock beforeEach(async () => { - ;({ history, store } = await createStore()) + ;({ store } = await createStore()) onCloseMock = vi.fn() }) @@ -195,13 +193,13 @@ describe('user audit action modal tests', () => { describe('in case of successful deactivate audit action', () => { beforeEach(async () => { const [successMock] = graphqlMocksOfDeactivate - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: [successMock] } + { store, graphqlMocks: [successMock] } ) component = testComponent }) @@ -257,14 +255,15 @@ describe('user audit action modal tests', () => { describe('in case of failed deactivate audit action', () => { beforeEach(async () => { const [, errorMock] = graphqlMocksOfDeactivate - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: [errorMock] } + { store, graphqlMocks: [errorMock] } ) + component = testComponent }) describe('after filling mandatory data', () => { @@ -290,13 +289,13 @@ describe('user audit action modal tests', () => { describe('in case of successful reactivate audit action', () => { beforeEach(async () => { const [successMock] = graphqlMocksOfReactivate - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: [successMock] } + { store, graphqlMocks: [successMock] } ) component = testComponent }) @@ -339,14 +338,15 @@ describe('user audit action modal tests', () => { describe('in case of failed reactivate audit action', () => { beforeEach(async () => { const [, errorMock] = graphqlMocksOfReactivate - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history, graphqlMocks: [errorMock] } + { store, graphqlMocks: [errorMock] } ) + component = testComponent }) describe('after filling mandatory data', () => { diff --git a/packages/client/src/views/SysAdmin/Team/user/UserList.test.tsx b/packages/client/src/views/SysAdmin/Team/user/UserList.test.tsx index 8002a5aad41..0ff7ec194ac 100644 --- a/packages/client/src/views/SysAdmin/Team/user/UserList.test.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/UserList.test.tsx @@ -14,12 +14,12 @@ import { createTestComponent, flushPromises, mockOfflineDataDispatch, - mockUserResponse + mockUserResponse, + TestComponentWithRouteMock } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' import { SEARCH_USERS } from '@client/user/queries' import { ReactWrapper } from 'enzyme' -import { History } from 'history' import { stringify } from 'query-string' import * as React from 'react' import { UserList } from './UserList' @@ -27,14 +27,14 @@ import { userMutations } from '@client/user/mutations' import * as actions from '@client/profile/profileActions' import { offlineDataReady } from '@client/offline/actions' import { vi, Mock } from 'vitest' +import { TEAM_USER_LIST } from '@client/navigation/routes' describe('user list without admin scope', () => { let store: AppStore - let history: History it('no add user button', async () => { Date.now = vi.fn(() => 1487076708000) - ;({ store, history } = await createStore()) + ;({ store } = await createStore()) const action = { type: actions.SET_USER_DETAILS, payload: mockUserResponse @@ -63,7 +63,7 @@ describe('user list without admin scope', () => { } ] - const component = await createTestComponent( + const { component } = await createTestComponent( { }) }} />, - { store, history, graphqlMocks: userListMock } + { + store, + graphqlMocks: userListMock, + initialEntries: [ + '/' + + '?' + + stringify({ + locationId: '0d8474da-0361-4d32-979e-af91f012340a' + }) + ] + } ) + component.update() expect(component.find('#add-user').length).toBe(0) }) @@ -81,11 +92,10 @@ describe('user list without admin scope', () => { describe('User list tests', () => { let store: AppStore - let history: History beforeAll(async () => { Date.now = vi.fn(() => 1487076708000) - ;({ store, history } = await createStore()) + ;({ store } = await createStore()) const action = { type: actions.SET_USER_DETAILS, @@ -118,24 +128,26 @@ describe('User list tests', () => { } } ] - const component = await createTestComponent( - , { + store, + path: TEAM_USER_LIST, + initialEntries: [ + '/', + TEAM_USER_LIST + + '?' + + stringify({ locationId: '0d8474da-0361-4d32-979e-af91f012340a' }) - }} - />, - { store, history, graphqlMocks: userListMock } - ) + ], + graphqlMocks: userListMock + }) component.update() const addUser = await waitForElement(component, '#add-user') addUser.hostNodes().simulate('click') component.update() - expect(history.location.pathname).toContain('/createUserInLocation') + expect(router.state.location.pathname).toContain('/createUserInLocation') }) it('add user button redirects to office selection form for invalid location id', async () => { const userListMock = [ @@ -158,17 +170,18 @@ describe('User list tests', () => { } } ] - const component = await createTestComponent( - , { + store, + path: TEAM_USER_LIST, + initialEntries: [ + TEAM_USER_LIST + + '?' + + stringify({ locationId: '0d8474da-0361-4d32-979e-af91f012340a' }) - }} - />, - { store, history, graphqlMocks: userListMock } - ) + ], + graphqlMocks: userListMock + }) component.update() const addUser = await waitForElement(component, '#add-user') @@ -176,7 +189,7 @@ describe('User list tests', () => { component.update() - expect(history.location.pathname).toContain('/createUser') + expect(router.state.location.pathname).toContain('/createUser') }) }) @@ -202,17 +215,19 @@ describe('User list tests', () => { } } ] - const testComponent = await createTestComponent( - // @ts-ignore - , - { store, history, graphqlMocks: userListMock } + const { component: testComponent } = await createTestComponent( + , + { + store, + initialEntries: [ + TEAM_USER_LIST + + '?' + + stringify({ + locationId: '0d8474da-0361-4d32-979e-af91f012340a' + }) + ], + graphqlMocks: userListMock + } ) // wait for mocked data to load mockedProvider @@ -230,6 +245,7 @@ describe('User list tests', () => { userMutations.usernameReminderSend = vi.fn() userMutations.sendResetPasswordInvite = vi.fn() let component: ReactWrapper<{}, {}> + let router: TestComponentWithRouteMock['router'] const userListMock = [ { request: { @@ -333,17 +349,20 @@ describe('User list tests', () => { configurable: true, value: 1100 }) - const testComponent = await createTestComponent( - , - { store, history, graphqlMocks: userListMock } - ) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: TEAM_USER_LIST, + initialEntries: [ + '/', + TEAM_USER_LIST + + '?' + + stringify({ + locationId: '0d8474da-0361-4d32-979e-af91f012340a' + }) + ], + graphqlMocks: userListMock + }) // wait for mocked data to load mockedProvider await new Promise((resolve) => { @@ -352,6 +371,7 @@ describe('User list tests', () => { testComponent.update() component = testComponent + router = testRouter }) it('renders list of users', () => { @@ -389,7 +409,9 @@ describe('User list tests', () => { .at(0) menuOptionButton.hostNodes().simulate('click') await flushPromises() - expect(history.location.pathname).toMatch(/.user\/(\w)+\/preview\/*/) + expect(router.state.location.pathname).toMatch( + /.user\/(\w)+\/preview\/*/ + ) }) it('clicking on menu options Resend invite sends invite', async () => { @@ -748,7 +770,7 @@ describe('User list tests', () => { } } ] - const testComponent = await createTestComponent( + const {router: testComponent} = await createTestComponent( { } } ] - const testComponent = await createTestComponent( + const {router: testComponent} = await createTestComponent( { } } ] - const testComponent = await createTestComponent( + const {router: testComponent} = await createTestComponent( { let store: AppStore - let history: History let testComponent: ReactWrapper + let testRouter: TestComponentWithRouteMock['router'] beforeEach(async () => { ;(roleQueries.fetchRoles as Mock).mockReturnValue(mockRoles) ;(userQueries.searchUsers as Mock).mockReturnValue(mockUsers) const s = createStore() store = s.store - history = s.history store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() }) describe('when user is in create new user form', () => { beforeEach(async () => { - testComponent = await createTestComponent( - , - { store, history } - ) + const component = await createTestComponent(, { + store, + path: CREATE_USER_ON_LOCATION, + initialEntries: [ + formatUrl(CREATE_USER_ON_LOCATION, { + locationId: '0d8474da-0361-4d32-979e-af91f012340a', + sectionId: mockOfflineData.userForms.sections[0].id + }) + ] + }) + + testComponent = component.component + testRouter = component.router loginAsFieldAgent(store) }) @@ -241,7 +242,7 @@ describe('create new user tests', () => { await waitForElement(testComponent, '#confirm_form') testComponent.find('#confirm_form').hostNodes().simulate('click') await flushPromises() - expect(history.location.pathname).toContain( + expect(testRouter.state.location.pathname).toContain( 'preview/preview-registration-office' ) }) @@ -252,7 +253,7 @@ describe('create new user tests', () => { testComponent.find('#confirm_form').hostNodes().simulate('click') await flushPromises() - expect(history.location.pathname).toContain( + expect(testRouter.state.location.pathname).toContain( '/createUser/user/signature-attachment' ) }) @@ -260,24 +261,23 @@ describe('create new user tests', () => { describe('when user in review page', () => { beforeEach(async () => { - store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() + + store.dispatch(offlineDataReady(mockOfflineDataDispatch)) store.dispatch(modifyUserFormData(mockCompleteFormData)) - testComponent = await createTestComponent( - // @ts-ignore - , { + store, + path: CREATE_USER_SECTION, + initialEntries: [ + formatUrl(CREATE_USER_SECTION, { sectionId: mockOfflineData.userForms.sections[1].id, groupId: mockOfflineData.userForms.sections[1].groups[0].id - }, - isExact: true, - path: '/createUser', - url: '' - }} - />, - { store, history } - ) + }) + ] + })) }) it('renders review header', () => { @@ -293,8 +293,10 @@ describe('create new user tests', () => { .first() .simulate('click') await flushPromises() - expect(history.location.pathname).toBe('/createUser/user/user-view-group') - expect(history.location.hash).toBe('#firstName') + expect(testRouter.state.location.pathname).toBe( + '/createUser/user/user-view-group' + ) + expect(testRouter.state.location.hash).toBe('#firstName') }) it('clicking submit button submits the form data', async () => { @@ -308,8 +310,9 @@ describe('create new user tests', () => { }) describe('edit user tests', () => { - const { store, history } = createStore() + const { store } = createStore() let component: ReactWrapper<{}, {}> + let router: Router const submitMock: Mock = vi.fn() const graphqlMocks = [ @@ -384,24 +387,22 @@ describe('edit user tests', () => { describe('when user is in update form page', () => { beforeEach(async () => { - const testComponent = await createTestComponent( - // @ts-ignore - , { + store, + graphqlMocks: graphqlMocks, + path: REVIEW_USER_FORM, + initialEntries: [ + formatUrl(REVIEW_USER_FORM, { userId: '5e835e4d81fbf01e4dc554db', sectionId: UserSection.User, groupId: 'user-view-group' - }, - isExact: true, - path: REVIEW_USER_FORM, - url: '' - }} - />, - { store, history, graphqlMocks: graphqlMocks } - ) + }) + ] + }) component = testComponent + router = testRouter }) it('clicking on continue button takes user signature attachment page', async () => { @@ -414,41 +415,30 @@ describe('edit user tests', () => { component.update() await flushPromises() - expect(history.location.pathname).toContain('signature-attachment') + expect(router.state.location.pathname).toContain('signature-attachment') }) }) describe('when user is in review page', () => { beforeEach(async () => { - const testComponent = await createTestComponent( + ;({ component, router } = await createTestComponent( , + { + store, + graphqlMocks, + path: REVIEW_USER_DETAILS, + initialEntries: [ + formatUrl(REVIEW_USER_DETAILS, { userId: '5e835e4d81fbf01e4dc554db', sectionId: UserSection.Preview - }, - isExact: true, - path: REVIEW_USER_FORM, - url: '' - }} - />, - { store, history, graphqlMocks } - ) + }) + ] + } + )) - // wait for mocked data to load mockedProvider - await new Promise((resolve) => { - setTimeout(resolve, 100) - }) - component = testComponent component.update() }) @@ -464,18 +454,17 @@ describe('edit user tests', () => { ) changeButtonOfType.hostNodes().first().simulate('click') await flushPromises() - expect(history.location.hash).toBe('#device') + expect(router.state.location.hash).toBe('#device') }) it('clicking confirm button starts submitting the form', async () => { - await waitForElement(component, '#submit-edit-user-form') - component.update() - const submitButton = await waitForElement( component, '#submit-edit-user-form' ) + submitButton.hostNodes().simulate('click') + expect(store.getState().userForm.submitting).toBe(true) }) }) diff --git a/packages/client/src/views/SysAdmin/Team/user/userCreation/CreateNewUser.tsx b/packages/client/src/views/SysAdmin/Team/user/userCreation/CreateNewUser.tsx index 7f29829c590..8856cfee6da 100644 --- a/packages/client/src/views/SysAdmin/Team/user/userCreation/CreateNewUser.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/userCreation/CreateNewUser.tsx @@ -30,7 +30,7 @@ import { ActionPageLight } from '@opencrvs/components/lib/ActionPageLight' import { Spinner } from '@opencrvs/components/lib/Spinner' import { ApolloClient } from '@apollo/client' import { withApollo, WithApolloClient } from '@apollo/client/react/hoc' -import React, { useEffect } from 'react' +import * as React from 'react' import { injectIntl, WrappedComponentProps as IntlShapeProps } from 'react-intl' import { connect } from 'react-redux' import { gqlToDraftTransformer } from '@client/transformer' @@ -38,7 +38,10 @@ import { messages as userFormMessages } from '@client/i18n/messages/views/userFo import { CREATE_USER_ON_LOCATION } from '@client/navigation/routes' import { getOfflineData } from '@client/offline/selectors' import { getUserDetails } from '@client/profile/profileSelectors' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' type IUserProps = { userId?: string @@ -80,89 +83,77 @@ const SpinnerWrapper = styled.div` align-items: center; ` -const CreateNewUserComponent = (props: WithApolloClient) => { - const { - userId, - intl, - submitting, - clearUserFormData, - fetchAndStoreUserData, - client, - section, - userDetailsStored, - loadingRoles, - router - } = props - - useEffect(() => { - const initialize = async () => { - //@Todo validate if this is right: - if ( - router.location.pathname.includes( - CREATE_USER_ON_LOCATION.split('/:')[0] - ) - ) { - clearUserFormData() - } - if (userId) { - fetchAndStoreUserData(client as ApolloClient, GET_USER, { - userId - }) - } - } - - initialize() - - return () => { - clearUserFormData() +class CreateNewUserComponent extends React.Component> { + async componentDidMount() { + const { userId, client } = this.props + if ( + this.props.router.location.pathname.includes( + CREATE_USER_ON_LOCATION.split('/:')[0] + ) + ) { + this.props.clearUserFormData() } - }, [ - userId, - clearUserFormData, - fetchAndStoreUserData, - client, - router.location.pathname - ]) - - const renderLoadingPage = () => ( - , GET_USER, { userId - ? intl.formatMessage(sysAdminMessages.editUserDetailsTitle) - : intl.formatMessage(formMessages.userFormTitle) - } - goBack={() => router.navigate(-1)} - hideBackground={true} - > - - {submitting ? ( - - -

- {userId - ? intl.formatMessage(userFormMessages.updatingUser) - : intl.formatMessage(userFormMessages.creatingNewUser)} -

-
- ) : ( - - )} -
-
- ) + }) + } + } - if (submitting || loadingRoles || (userId && !userDetailsStored)) { - return renderLoadingPage() + async componentWillUnmount() { + this.props.clearUserFormData() } - if (section.viewType === 'form') { - return + renderLoadingPage = () => { + const { intl, userId } = this.props + return ( + this.props.router.navigate(-1)} + hideBackground={true} + > + + {this.props.submitting ? ( + + +

+ {this.props.userId + ? intl.formatMessage(userFormMessages.updatingUser) + : intl.formatMessage(userFormMessages.creatingNewUser)} +

+
+ ) : ( + + )} +
+
+ ) } - if (section.viewType === 'preview') { - return } {...props} /> + render() { + const { section, submitting, userDetailsStored, loadingRoles, userId } = + this.props + if (submitting || loadingRoles || (userId && !userDetailsStored)) { + return this.renderLoadingPage() + } + + if (section.viewType === 'form') { + return + } + + if (section.viewType === 'preview') { + return ( + } + {...this.props} + /> + ) + } } - return null } function getNextSectionIds( diff --git a/packages/client/src/views/SysAdmin/Team/user/userCreation/SignatureForm.test.tsx b/packages/client/src/views/SysAdmin/Team/user/userCreation/SignatureForm.test.tsx index 326f979a0aa..5416573277e 100644 --- a/packages/client/src/views/SysAdmin/Team/user/userCreation/SignatureForm.test.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/userCreation/SignatureForm.test.tsx @@ -32,10 +32,14 @@ import { ReactWrapper } from 'enzyme' import * as React from 'react' import { roleQueries } from '@client/forms/user/query/queries' import { Mock, describe, expect } from 'vitest' +import { formatUrl } from '@client/navigation' +import { CREATE_USER_SECTION } from '@client/navigation/routes' +import { Router } from '@sentry/react/types/types' describe('signature upload tests', () => { - const { store, history } = createStore() + const { store } = createStore() let testComponent: ReactWrapper + let router: Router beforeEach(async () => { ;(roleQueries.fetchRoles as Mock).mockReturnValue(mockRoles) @@ -46,21 +50,19 @@ describe('signature upload tests', () => { describe('when user is in signature upload form page', () => { beforeEach(async () => { ;(roleQueries.fetchRoles as Mock).mockReturnValue(mockRoles) - testComponent = await createTestComponent( - // @ts-ignore - , + { + store, + path: CREATE_USER_SECTION, + initialEntries: [ + formatUrl(CREATE_USER_SECTION, { sectionId: mockOfflineData.userForms.sections[0].id, groupId: mockOfflineData.userForms.sections[0].groups[2].id - }, - isExact: true, - path: '/createUser', - url: '' - }} - />, - { store, history } - ) + }) + ] + } + )) }) it('show the signature form page', async () => { @@ -123,7 +125,7 @@ describe('signature upload tests', () => { await flushPromises() testComponent.update() - expect(history.location.pathname).toContain( + expect(router.state.location.pathname).toContain( '/createUser/preview/preview-registration-office' ) }) @@ -131,30 +133,26 @@ describe('signature upload tests', () => { describe('when user in review page', () => { beforeEach(async () => { + await flushPromises() store.dispatch(modifyUserFormData(mockDataWithRegistarRoleSelected)) store.dispatch(rolesMessageAddData()) - testComponent = await createTestComponent( - // @ts-ignore - , + ;({ component: testComponent } = await createTestComponent( + , { store, - history, + path: CREATE_USER_SECTION, + initialEntries: [ + formatUrl(CREATE_USER_SECTION, { + sectionId: mockOfflineData.userForms.sections[1].id, + groupId: mockOfflineData.userForms.sections[1].groups[0].id + }) + ], graphqlMocks: [ mockFetchRoleGraphqlOperation, mockUserGraphqlOperation ] } - ) + )) }) it('renders review header', () => { diff --git a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.test.tsx b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.test.tsx index 964c009653f..5ee5f1295c6 100644 --- a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.test.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.test.tsx @@ -24,14 +24,14 @@ import * as React from 'react' import { waitForElement } from '@client/tests/wait-for-element' import * as builtInValidators from '@client/utils/validate' -const { store, history } = createStore() +const { store } = createStore() describe('Create new user page tests', () => { let component: ReactWrapper beforeEach(async () => { store.dispatch(offlineDataReady(mockOfflineDataDispatch)) await flushPromises() - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { nextGroupId="preview-user-view-group" nextSectionId="preview" />, - { store, history } + { store } ) component = testComponent }) diff --git a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.tsx b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.tsx index b3274a0efba..02569720ce9 100644 --- a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserForm.tsx @@ -47,7 +47,10 @@ import { Content, ContentSize } from '@opencrvs/components/lib/Content' import { selectSystemRoleMap } from '@client/user/selectors' import { UserDetails } from '@client/utils/userUtils' import { getUserDetails } from '@client/profile/profileSelectors' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' +import { + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' import * as routes from '@client/navigation/routes' import { stringify } from 'query-string' diff --git a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserReviewForm.tsx b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserReviewForm.tsx index 6ee979d7f2c..b2d2741ef1b 100644 --- a/packages/client/src/views/SysAdmin/Team/user/userCreation/UserReviewForm.tsx +++ b/packages/client/src/views/SysAdmin/Team/user/userCreation/UserReviewForm.tsx @@ -40,20 +40,18 @@ import { getOfflineData } from '@client/offline/selectors' import { IStoreState } from '@client/store' import { draftToGqlTransformer } from '@client/transformer' import { - clearUserFormData, modifyUserFormData, - submitFail, - submitSuccess + submitUserFormData } from '@client/user/userReducer' import { Action } from '@client/views/SysAdmin/Team/user/userCreation/UserForm' import { SuccessButton, ICON_ALIGNMENT } from '@opencrvs/components/lib/buttons' import { Button } from '@opencrvs/components/lib/Button' import { IDynamicValues } from '@opencrvs/components/lib/common-types' import { ActionPageLight } from '@opencrvs/components/lib/ActionPageLight' -import { ApolloClient, useMutation } from '@apollo/client' +import { ApolloClient } from '@apollo/client' import * as React from 'react' import { injectIntl, WrappedComponentProps as IntlShapeProps } from 'react-intl' -import { connect, useDispatch } from 'react-redux' +import { connect } from 'react-redux' import { Dispatch } from 'redux' import { messages as sysAdminMessages } from '@client/i18n/messages/views/sysAdmin' import { Check } from '@opencrvs/components/lib/icons' @@ -68,12 +66,11 @@ import styled from 'styled-components' import { Content } from '@opencrvs/components/lib/Content' import { getUserRoleIntlKey } from '@client/views/SysAdmin/Team/utils' import { Link } from '@opencrvs/components' -import { RouteComponentProps, withRouter } from '@client/components/withRouter' -import { useNavigate, useParams } from 'react-router-dom' import { - CreateOrUpdateUserMutation, - CreateOrUpdateUserMutationVariables -} from '@client/utils/gateway' + RouteComponentProps, + withRouter +} from '@client/components/WithRouterProps' +import { useNavigate } from 'react-router-dom' import * as routes from '@client/navigation/routes' import { stringify } from 'query-string' @@ -88,6 +85,7 @@ interface IDispatchProps { userFormSection: IFormSection offlineCountryConfiguration: IOfflineData modify: (values: IFormSectionData) => void + submitForm: (variables: Record) => void userDetails: UserDetails | null } @@ -126,35 +124,13 @@ const UserReviewFormComponent = ({ formData, offlineCountryConfiguration, userId, - section + section, + submitForm }: IFullProps & IDispatchProps) => { const navigate = useNavigate() - const params = useParams() - const dispatch = useDispatch() const locationId = formData['registrationOffice'] - const [createOrUpdateUser] = useMutation< - CreateOrUpdateUserMutation, - CreateOrUpdateUserMutationVariables - >(createOrUpdateUserMutation, { - onError(error, clientOptions) { - dispatch(submitFail(error)) - }, - onCompleted() { - dispatch(clearUserFormData) - - navigate({ - pathname: routes.TEAM_USER_LIST, - search: stringify({ - locationId - }) - }) - - dispatch(submitSuccess(Boolean(params.userId))) - } - }) - const getValue = (field: IFormField) => { if (field.type === LOCATION_SEARCH_INPUT) { const offlineLocations = field.searchableResource.reduce( @@ -306,9 +282,7 @@ const UserReviewFormComponent = ({ delete variables.user.signature.__typename //to fix updating registrar bug } - createOrUpdateUser({ - variables: variables as CreateOrUpdateUserMutationVariables - }) + submitForm(variables) } let title: string | undefined @@ -409,8 +383,28 @@ const UserReviewFormComponent = ({ } const mapDispatchToProps = (dispatch: Dispatch, props: IFullProps) => { + const navigateToUserList = () => + props.router.navigate({ + pathname: routes.TEAM_USER_LIST, + search: stringify({ + locationId: props.formData.registrationOffice as string + }) + }) + return { - modify: (values: IFormSectionData) => dispatch(modifyUserFormData(values)) + modify: (values: IFormSectionData) => dispatch(modifyUserFormData(values)), + submitForm: (variables: Record) => { + dispatch( + submitUserFormData( + props.client, + createOrUpdateUserMutation, + variables, + props.formData.registrationOffice as string, + Boolean(props.router.match.params.userId), // to detect if update or create, + navigateToUserList + ) + ) + } } } export const UserReviewForm = withRouter( diff --git a/packages/client/src/views/Unlock/ForgotPIN.test.tsx b/packages/client/src/views/Unlock/ForgotPIN.test.tsx index 36bd1e63e3f..d93f262e867 100644 --- a/packages/client/src/views/Unlock/ForgotPIN.test.tsx +++ b/packages/client/src/views/Unlock/ForgotPIN.test.tsx @@ -20,20 +20,18 @@ import { userQueries } from '@client/user/queries' import { storage } from '@client/storage' import { SCREEN_LOCK } from '@client/components/ProtectedPage' import { SECURITY_PIN_EXPIRED_AT } from '@client/utils/constants' -import { History } from 'history' import { vi, Mock } from 'vitest' import { SystemRoleType, Status } from '@client/utils/gateway' describe('ForgotPIN tests', () => { let component: ReactWrapper let store: AppStore - let history: History const goBackMock: Mock = vi.fn() const onVerifyPasswordMock = vi.fn() userQueries.verifyPasswordById = vi.fn() beforeAll(async () => { - ;({ store, history } = await createStore()) + ;({ store } = await createStore()) store.dispatch( setUserDetails({ @@ -84,10 +82,11 @@ describe('ForgotPIN tests', () => { }) beforeEach(async () => { - component = await createTestComponent( + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) + component = testComponent // wait for mocked data to load mockedProvider await new Promise((resolve) => { diff --git a/packages/client/src/views/Unlock/Unlock.test.tsx b/packages/client/src/views/Unlock/Unlock.test.tsx index 3c589667fe6..f8c75c6e415 100644 --- a/packages/client/src/views/Unlock/Unlock.test.tsx +++ b/packages/client/src/views/Unlock/Unlock.test.tsx @@ -70,11 +70,11 @@ describe('Unlock page loads Properly', () => { async (key: string, value: string) => (indexedDB[key] = value) ) - const { store, history } = createStore() - testComponent = await createTestComponent( + const { store } = createStore() + ;({ component: testComponent } = await createTestComponent( null} onForgetPin={onForgetPinMock} />, - { store, history } - ) + { store } + )) }) it('Should load the Unlock page properly', () => { @@ -108,11 +108,12 @@ describe('For wrong inputs', () => { beforeEach(async () => { await flushPromises() vi.clearAllMocks() - const { store, history } = createStore() - testComponent = await createTestComponent( + const { store } = createStore() + + ;({ component: testComponent } = await createTestComponent( null} onForgetPin={onForgetPinMock} />, - { store, history } - ) + { store } + )) // These tests are only for wrong inputs, so this mock fn only returns a promise of false pinValidator.isValidPin = vi.fn(async (pin) => Promise.resolve(false)) @@ -178,11 +179,11 @@ describe('Pin locked session', () => { async (key: string, value: string) => (indexedDB[key] = value) ) - const { store, history } = createStore() - testComponent = await createTestComponent( + const { store } = createStore() + ;({ component: testComponent } = await createTestComponent( null} onForgetPin={onForgetPinMock} />, - { store, history } - ) + { store } + )) }) it('Should not accept correct pin while the account is locked', async () => { @@ -205,14 +206,14 @@ describe('Logout Sequence', () => { const onForgetPinMock: Mock = vi.fn() it('should clear lock-related indexeddb entries upon logout', async () => { - const { store, history } = createStore() + const { store } = createStore() const redirect = vi.fn() - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( redirect} onForgetPin={onForgetPinMock} />, - { store, history } + { store } ) const indexeddb = { SCREEN_LOCK: true, diff --git a/packages/client/src/views/UserAudit/UserAudit.test.tsx b/packages/client/src/views/UserAudit/UserAudit.test.tsx index ddcab7460bc..aeca6f96c68 100644 --- a/packages/client/src/views/UserAudit/UserAudit.test.tsx +++ b/packages/client/src/views/UserAudit/UserAudit.test.tsx @@ -16,19 +16,19 @@ import { userDetails } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' -import { ReactWrapper } from 'enzyme' -import { History } from 'history' -import * as React from 'react' +import { userMutations } from '@client/user/mutations' import { GET_USER } from '@client/user/queries' import { UserAudit } from '@client/views/UserAudit/UserAudit' -import { userMutations } from '@client/user/mutations' -import { vi, Mock } from 'vitest' -import * as Router from 'react-router-dom' +import { ReactWrapper } from 'enzyme' +import * as React from 'react' +import { vi } from 'vitest' + +import { formatUrl } from '@client/navigation' +import { USER_PROFILE } from '@client/navigation/routes' import { getStorageUserDetailsSuccess } from '@client/profile/profileActions' -import { SystemRoleType } from '@client/utils/gateway' import * as profileSelectors from '@client/profile/profileSelectors' - -const useParams = Router.useParams as Mock +import { SystemRoleType } from '@client/utils/gateway' +import { createMemoryRouter } from 'react-router-dom' const mockAuditedUserGqlResponse = { request: { @@ -87,24 +87,24 @@ describe('User audit list tests for field agent', () => { userMutations.resendInvite = vi.fn() let component: ReactWrapper<{}, {}> let store: AppStore - let history: History + let router: ReturnType beforeEach(async () => { Date.now = vi.fn(() => 1487076708000) - useParams.mockImplementation(() => ({ - userId: '5d08e102542c7a19fc55b790' - })) - - const { store: testStore, history: testHistory } = await createTestStore() + const { store: testStore } = await createTestStore() store = testStore - history = testHistory store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - component = await createTestComponent(, { + ;({ component, router } = await createTestComponent(, { store, - history, + path: USER_PROFILE, + initialEntries: [ + formatUrl(USER_PROFILE, { + userId: '5d08e102542c7a19fc55b790' + }) + ], graphqlMocks: [mockAuditedUserGqlResponse] - }) + })) }) it('renders without crashing', async () => { @@ -112,11 +112,13 @@ describe('User audit list tests for field agent', () => { }) it('renders with a error toast for graphql error', async () => { - const testComponent = await createTestComponent(, { - store, - history, - graphqlMocks: [] - }) + const { component: testComponent } = await createTestComponent( + , + { + store, + graphqlMocks: [] + } + ) expect(await waitForElement(testComponent, '#error-toast')).toBeDefined() }) @@ -128,26 +130,21 @@ describe('User audit list tests for field agent', () => { await new Promise((resolve) => { setTimeout(resolve, 100) }) - expect(history.location.pathname).toBe('/team/users') + expect(router.state.location.pathname).toBe('/team/users') }) }) describe('User audit list tests for sys admin', () => { userMutations.resendInvite = vi.fn() let component: ReactWrapper<{}, {}> + let router: ReturnType let store: AppStore - let history: History beforeEach(async () => { Date.now = vi.fn(() => 1487076708000) - useParams.mockImplementation(() => ({ - userId: '5d08e102542c7a19fc55b790' - })) - - const { store: testStore, history: testHistory } = await createTestStore() + const { store: testStore } = await createTestStore() store = testStore - history = testHistory userDetails.systemRole = SystemRoleType.LocalSystemAdmin userDetails.primaryOffice = { id: '895cc945-94a9-4195-9a29-22e9310f3385', @@ -157,11 +154,19 @@ describe('User audit list tests for sys admin', () => { } vi.spyOn(profileSelectors, 'getScope').mockReturnValue(['sysadmin']) store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - component = await createTestComponent(, { - store, - history, - graphqlMocks: [mockAuditedUserGqlResponse] - }) + const { component: testComponent, router: testRouter } = + await createTestComponent(, { + store, + path: USER_PROFILE, + initialEntries: [ + formatUrl(USER_PROFILE, { + userId: '5d08e102542c7a19fc55b790' + }) + ], + graphqlMocks: [mockAuditedUserGqlResponse] + }) + component = testComponent + router = testRouter }) it('redirects to edit user view on clicking edit details menu option', async () => { @@ -186,7 +191,7 @@ describe('User audit list tests for sys admin', () => { // wait for mocked data to load mockedProvider await flushPromises() - expect(history.location.pathname).toBe( + expect(router.state.location.pathname).toBe( '/user/5d08e102542c7a19fc55b790/preview/' ) }) diff --git a/packages/client/src/views/UserAudit/UserAuditHistory.test.tsx b/packages/client/src/views/UserAudit/UserAuditHistory.test.tsx index 07161a734ba..4b1f3a54150 100644 --- a/packages/client/src/views/UserAudit/UserAuditHistory.test.tsx +++ b/packages/client/src/views/UserAudit/UserAuditHistory.test.tsx @@ -8,26 +8,20 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ +import { formatUrl } from '@client/navigation' +import { TEAM_USER_LIST } from '@client/navigation/routes' import { AppStore } from '@client/store' -import { - createRouterProps, - createTestComponent, - createTestStore -} from '@client/tests/util' +import { createTestComponent, createTestStore } from '@client/tests/util' import { waitForElement } from '@client/tests/wait-for-element' -import { ReactWrapper } from 'enzyme' -import * as React from 'react' import { GET_USER_AUDIT_LOG } from '@client/user/queries' import { UserAuditHistory } from '@client/views/UserAudit/UserAuditHistory' -import { History } from 'history' +import { ReactWrapper } from 'enzyme' +import * as React from 'react' import { vi } from 'vitest' -import { TEAM_USER_LIST } from '@client/navigation/routes' -import { formatUrl } from '@client/navigation' describe('User audit list tests', () => { let component: ReactWrapper<{}, {}> let store: AppStore - let history: History const graphqlMock = [ { @@ -175,26 +169,22 @@ describe('User audit list tests', () => { beforeEach(async () => { Date.now = vi.fn(() => 1487076708000) - ;({ store, history } = await createTestStore()) - component = await createTestComponent( + ;({ store } = await createTestStore()) + const { component: testComponent } = await createTestComponent( // @ts-ignore - , + { + store, + path: TEAM_USER_LIST, + initialEntries: [ formatUrl(TEAM_USER_LIST, { userId: '5d08e102542c7a19fc55b790' - }), - { isNavigatedInsideApp: false }, - { - matchParams: { - userId: '5d08e102542c7a19fc55b790' - } - } - )} - />, - { store, history, graphqlMocks: graphqlMock } + }) + ], + graphqlMocks: graphqlMock + } ) - + component = testComponent // wait for mocked data to load mockedProvider await new Promise((resolve) => { setTimeout(resolve, 100) @@ -208,25 +198,22 @@ describe('User audit list tests', () => { }) it('renders in loading mode', async () => { - const testComponent = await createTestComponent( + const { component } = await createTestComponent( // @ts-ignore , { - store, - history + store } ) - expect( - await waitForElement(testComponent, '#loading-audit-list') - ).toBeDefined() + expect(await waitForElement(component, '#loading-audit-list')).toBeDefined() }) it('renders with a error toast for graphql error', async () => { - const testComponent = await createTestComponent( + const { component } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) - expect(await waitForElement(testComponent, '#error-toast')).toBeDefined() + expect(await waitForElement(component, '#error-toast')).toBeDefined() }) it('toggles sorting order of the list', async () => { const firstRowElement = await waitForElement(component, '#row_0') @@ -244,7 +231,7 @@ describe('User audit list tests', () => { }) it('renders next page of audits after clicking next page', async () => { - const testComponent = await createTestComponent( + const { component } = await createTestComponent( { />, { store, - history, graphqlMocks: [ graphqlMock[0], { @@ -292,14 +278,14 @@ describe('User audit list tests', () => { } ) - const nextPageButton = await waitForElement(testComponent, '#page-number-1') + const nextPageButton = await waitForElement(component, '#page-number-1') nextPageButton.hostNodes().find('button').first().simulate('click') // wait for query to go from loading to success await new Promise((resolve) => { setTimeout(resolve, 0) }) - testComponent.update() - const firstRow = await waitForElement(testComponent, '#row_0') + component.update() + const firstRow = await waitForElement(component, '#row_0') expect(firstRow.hostNodes().childAt(1).text()).toBe('D23S2D0') }) }) diff --git a/packages/client/src/views/UserSetup/CreatePassword.test.tsx b/packages/client/src/views/UserSetup/CreatePassword.test.tsx index 86e3efa0ac8..4fa0f72bc1a 100644 --- a/packages/client/src/views/UserSetup/CreatePassword.test.tsx +++ b/packages/client/src/views/UserSetup/CreatePassword.test.tsx @@ -14,15 +14,15 @@ import { createStore } from '@client/store' import { CreatePassword } from './CreatePassword' import { ReactWrapper } from 'enzyme' -const { store, history } = createStore() +const { store } = createStore() describe('CreatePassword page tests', () => { let component: ReactWrapper beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore {}} setupData={{ userId: '123' }} />, - { store, history } + { store } ) component = testComponent diff --git a/packages/client/src/views/UserSetup/SecurityQuestionView.test.tsx b/packages/client/src/views/UserSetup/SecurityQuestionView.test.tsx index 9fcdacecba3..48e4854a4d3 100644 --- a/packages/client/src/views/UserSetup/SecurityQuestionView.test.tsx +++ b/packages/client/src/views/UserSetup/SecurityQuestionView.test.tsx @@ -18,15 +18,15 @@ import { SecurityQuestion } from '@client/views/UserSetup/SecurityQuestionView' import { ReactWrapper } from 'enzyme' import * as React from 'react' -const { store, history } = createStore() +const { store } = createStore() describe('Security Question Page', () => { let component: ReactWrapper beforeEach(async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) component = testComponent component.find('button#submit-security-question').simulate('click') diff --git a/packages/client/src/views/UserSetup/SetupConfirmationPage.test.tsx b/packages/client/src/views/UserSetup/SetupConfirmationPage.test.tsx index 5ed1ed016bc..9f9034fe400 100644 --- a/packages/client/src/views/UserSetup/SetupConfirmationPage.test.tsx +++ b/packages/client/src/views/UserSetup/SetupConfirmationPage.test.tsx @@ -18,16 +18,16 @@ import { Mock } from 'vitest' const getItem = window.localStorage.getItem as Mock describe('Setup confirmation page tests', () => { - const { store, history } = createStore() + const { store } = createStore() beforeAll(async () => { getItem.mockReturnValue(validToken) await store.dispatch(checkAuth()) }) it('renders page successfully', async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) const app = testComponent expect(app.find('#user-setup-complete-page').hostNodes()).toHaveLength(1) diff --git a/packages/client/src/views/UserSetup/SetupReviewPage.test.tsx b/packages/client/src/views/UserSetup/SetupReviewPage.test.tsx index 0e67d94eb37..49f658d0428 100644 --- a/packages/client/src/views/UserSetup/SetupReviewPage.test.tsx +++ b/packages/client/src/views/UserSetup/SetupReviewPage.test.tsx @@ -8,14 +8,14 @@ * * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS. */ -import * as React from 'react' +import { createStore } from '@client/store' import { createTestComponent, userDetails } from '@client/tests/util' import { getStorageUserDetailsSuccess } from '@opencrvs/client/src/profile/profileActions' -import { createStore } from '@client/store' +import * as React from 'react' import { UserSetupReview } from './SetupReviewPage' import { activateUserMutation } from './queries' -const { store, history } = createStore() +const { store } = createStore() describe('SetupReviewPage page tests', () => { beforeEach(async () => { @@ -38,7 +38,7 @@ describe('SetupReviewPage page tests', () => { }) ) ) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { }} goToStep={() => {}} />, - { store, history } + { store } ) expect(testComponent.find('#UserSetupData')).toBeDefined() }) it('render page without type', async () => { store.dispatch(getStorageUserDetailsSuccess(JSON.stringify(userDetails))) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { }} goToStep={() => {}} />, - { store, history } + { store } ) const role = testComponent.find('#Role_value').hostNodes().text() expect(role).toEqual('ENTREPENEUR') }) it('clicks question to change', async () => { - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { }} goToStep={() => {}} />, - { store, history } + { store } ) testComponent @@ -113,7 +113,7 @@ describe('SetupReviewPage page tests', () => { } } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { ] }} />, - { store, history, graphqlMocks: mock } + { store, graphqlMocks: mock } ) testComponent.find('button#Confirm').simulate('click') @@ -147,7 +147,7 @@ describe('SetupReviewPage page tests', () => { } ] - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore { ] }} />, - { store, history, graphqlMocks: graphqlErrorMock } + { store, graphqlMocks: graphqlErrorMock } ) testComponent.find('button#Confirm').simulate('click') diff --git a/packages/client/src/views/UserSetup/UserSetupPage.test.tsx b/packages/client/src/views/UserSetup/UserSetupPage.test.tsx index 336a5493e65..611343ff23a 100644 --- a/packages/client/src/views/UserSetup/UserSetupPage.test.tsx +++ b/packages/client/src/views/UserSetup/UserSetupPage.test.tsx @@ -25,7 +25,6 @@ import { } from '@client/profile/profileActions' import { UserSetupPage } from '@client/views/UserSetup/UserSetupPage' import { ProtectedAccount } from '@client/components/ProtectedAccount' -import { History } from 'history' import { Mock } from 'vitest' const nameObj = { @@ -51,28 +50,27 @@ merge(mockUserResponse, nameObj) describe('UserSetupPage tests', () => { let store: AppStore - let history: History + beforeEach(() => { - ;({ history, store } = createStore()) + ;({ store } = createStore()) }) it('renders page successfully without type', async () => { await store.dispatch( getStorageUserDetailsSuccess(JSON.stringify(userDetails)) ) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore , - { store, history } + { store } ) const app = testComponent expect(app.find('#user-setup-landing-page').hostNodes()).toHaveLength(1) }) it('go to password page', async () => { - const testComponent = await createTestComponent( - // @ts-ignore + const { component: testComponent } = await createTestComponent( , - { store, history } + { store } ) const app = testComponent @@ -83,10 +81,10 @@ describe('UserSetupPage tests', () => { it('go to password page without userDetails', async () => { await store.dispatch(checkAuth()) store.dispatch(getStorageUserDetailsSuccess('null')) - const testComponent = await createTestComponent( + const { component: testComponent } = await createTestComponent( // @ts-ignore {}} />, - { store, history } + { store } ) const app = testComponent diff --git a/packages/client/src/views/ViewRecord/ViewRecord.test.tsx b/packages/client/src/views/ViewRecord/ViewRecord.test.tsx index f6e8df374ba..abe538431af 100644 --- a/packages/client/src/views/ViewRecord/ViewRecord.test.tsx +++ b/packages/client/src/views/ViewRecord/ViewRecord.test.tsx @@ -15,14 +15,14 @@ import { createStore } from '@client/store' import { createTestComponent } from '@client/tests/util' import { FETCH_VIEW_RECORD_BY_COMPOSITION } from '@client/views/ViewRecord/query' import { ViewRecord } from './ViewRecord' -import { useParams } from 'react-router-dom' -import { Mock } from 'vitest' +import { VIEW_RECORD } from '@client/navigation/routes' +import { formatUrl } from '@client/navigation' describe('View Record for loading and success state', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() + const { store } = createStore() const mocks = [ { @@ -1202,13 +1202,16 @@ describe('View Record for loading and success state', () => { } } ] - component = await createTestComponent(, { + + ;({ component } = await createTestComponent(, { store, - history, + path: VIEW_RECORD, + initialEntries: [ + formatUrl(VIEW_RECORD, { + declarationId: '4090df15-f4e5-4f16-ae7e-bb518129d493' + }) + ], graphqlMocks: mocks - }) - ;(useParams as Mock).mockImplementation(() => ({ - declarationId: '4090df15-f4e5-4f16-ae7e-bb518129d493' })) }) @@ -1229,18 +1232,23 @@ describe('View Record error state', () => { let component: ReactWrapper<{}, {}> beforeEach(async () => { - const { store, history } = createStore() - component = await createTestComponent(, { - store, - history - }) + const { store } = createStore() + const { component: testComponent } = await createTestComponent( + , + { + store + } + ) + await new Promise((resolve) => { setTimeout(resolve, 0) }) - component.update() + + testComponent.update() + component = testComponent }) - it('Render error state properly ', async () => { + it('Render error state properly', async () => { expect(component.exists('GenericErrorToast')).toBeTruthy() }) })