Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1945: Unit test card search params #1947

Open
wants to merge 2 commits into
base: 1799-card-generator-refactoring
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MockedProvider as ApolloProvider } from '@apollo/client/testing'

Check warning on line 1 in administration/src/bp-modules/cards/hooks/useCardGenerator.test.tsx

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (1799-card-generator-refactoring)

❌ New issue: Code Duplication

The module contains 2 functions with similar structure: 'should show error message for failed card generation','should successfully create multiple cards'. Avoid duplicated, aka copy-pasted, code inside the module. More duplication lowers the code health.
import { OverlayToaster } from '@blueprintjs/core'
import { act, renderHook } from '@testing-library/react'
import { mocked } from 'jest-mock'
Expand All @@ -11,19 +11,16 @@
import deleteCards from '../../../cards/deleteCards'
import { DynamicActivationCode, StaticVerificationCode } from '../../../generated/card_pb'
import { Region } from '../../../generated/graphql'
import { ProjectConfigProvider } from '../../../project-configs/ProjectConfigContext'
import bayernConfig from '../../../project-configs/bayern/config'
import { ProjectConfig } from '../../../project-configs/getProjectConfig'
import nuernbergConfig from '../../../project-configs/nuernberg/config'
import showcaseConfig from '../../../project-configs/showcase/config'
import downloadDataUri from '../../../util/downloadDataUri'
import { AppToasterProvider } from '../../AppToaster'
import useCardGenerator from './useCardGenerator'

const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<AppToasterProvider>
<ApolloProvider>{children}</ApolloProvider>
</AppToasterProvider>
</MemoryRouter>
)

jest.useFakeTimers({ now: new Date('2025-01-01T00:00:00.000Z') })
jest.mock('../../../cards/PdfFactory', () => ({
...jest.requireActual('../../../cards/PdfFactory'),
generatePdf: jest.fn(),
Expand All @@ -35,6 +32,32 @@
}))
jest.mock('../../../cards/deleteCards')
jest.mock('../../../util/downloadDataUri')
const wrapper = ({
children,
initialRoutes,
projectConfig,
}: {
children: ReactNode
projectConfig?: ProjectConfig
initialRoutes?: string[]
}) => (
<MemoryRouter initialEntries={initialRoutes}>
<ProjectConfigProvider projectConfig={projectConfig ?? showcaseConfig}>
<AppToasterProvider>
<ApolloProvider>{children}</ApolloProvider>
</AppToasterProvider>
</ProjectConfigProvider>
</MemoryRouter>
)

const withCustomWrapper =
(projectConfig: ProjectConfig, initialRoute: string) =>
({ children }: { children: ReactNode }) =>
wrapper({
children,
initialRoutes: [initialRoute],
projectConfig,
})

describe('useCardGenerator', () => {
const region: Region = {
Expand Down Expand Up @@ -134,4 +157,55 @@
expect(result.current.cardGenerationStep).toBe('input')
expect(result.current.cards).toEqual([])
})

it('should successfully initialize cards with searchParams for bavaria', async () => {
mocked(createCards).mockReturnValueOnce(Promise.resolve(codes))
const { result } = renderHook(() => useCardGenerator({ region }), {
wrapper: withCustomWrapper(
bayernConfig,
'?Name=Thea+Test&Ablaufdatum=26.02.2028&MailNotification=thea.test%40gmail.com&applicationIdToMarkAsProcessed=1'
),
})

expect(result.current.cards).toEqual([
{
expirationDate: { day: 26, isoMonth: 2, isoYear: 2028 },
extensions: { bavariaCardType: 'Standard', regionId: 0, emailNotification: '[email protected]' },
fullName: 'Thea Test',
id: expect.any(Number),
},
])
})

it('should successfully initialize cards with searchParams for nuernberg', async () => {
mocked(createCards).mockReturnValueOnce(Promise.resolve(codes))
const { result } = renderHook(() => useCardGenerator({ region }), {
wrapper: withCustomWrapper(
nuernbergConfig,
'?Name=Thea+Test&Ablaufdatum=03.3.2026&Geburtsdatum=01.01.2000&Passnummer=12345678&Pass-ID=123&Adresszeile+1=Teststraße+3&Adresszeile+2=EG+Rechts&PLZ=86111&Ort=Musterstadt&Startdatum=01.05.2025'
),
})

expect(result.current.cards).toEqual([
{
expirationDate: { day: 3, isoMonth: 3, isoYear: 2026 },
extensions: {
birthday: {
day: 1,
isoMonth: 1,
isoYear: 2000,
},
addressLine1: 'Teststraße 3',
addressLine2: 'EG Rechts',
addressLocation: 'Musterstadt',
addressPlz: '86111',
nuernbergPassId: 123,
regionId: 0,
startDay: { day: 1, isoMonth: 5, isoYear: 2025 },
},
fullName: 'Thea Test',
id: expect.any(Number),
},
])
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,6 @@ import useCardGeneratorSelfService from '../useCardGeneratorSelfService'

const mocks: MockedResponse[] = []

const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<AppToasterProvider>
<MockedProvider mocks={mocks} addTypename={false}>
<ProjectConfigProvider projectConfig={koblenzConfig}>{children}</ProjectConfigProvider>
</MockedProvider>
</AppToasterProvider>
</MemoryRouter>
)

jest.mock('../../../../generated/graphql', () => ({
...jest.requireActual('../../../../generated/graphql'),
generatePdf: jest.fn(),
Expand All @@ -40,6 +30,24 @@ jest.mock('../../../../cards/PdfFactory', () => ({

jest.mock('../../../../util/downloadDataUri')

const wrapper = ({ children, initialRoutes }: { children: ReactNode; initialRoutes?: string[] }) => (
<MemoryRouter initialEntries={initialRoutes}>
<AppToasterProvider>
<MockedProvider mocks={mocks} addTypename={false}>
<ProjectConfigProvider projectConfig={koblenzConfig}>{children}</ProjectConfigProvider>
</MockedProvider>
</AppToasterProvider>
</MemoryRouter>
)

const withCustomWrapper =
(initialRoute: string) =>
({ children }: { children: ReactNode }) =>
wrapper({
children,
initialRoutes: [initialRoute],
})
Comment on lines +33 to +49
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙃 I guess we should make this reusable at some point to a shared testing file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes feel free to add a task for this


describe('useCardGeneratorSelfService', () => {
it('should successfully create a card', async () => {
const toasterSpy = jest.spyOn(OverlayToaster.prototype, 'show')
Expand All @@ -54,4 +62,25 @@ describe('useCardGeneratorSelfService', () => {
await act(async () => result.current.downloadPdf(result.current.code!, 'koblenzpass.pdf'))
expect(downloadDataUri).toHaveBeenCalled()
})

it('should successfully initialize cards with searchParams for koblenz', async () => {
jest.useFakeTimers({ now: new Date('2025-01-01T00:00:00.000Z') })
const { result } = renderHook(() => useCardGeneratorSelfService(), {
wrapper: withCustomWrapper('?Name=Karla Koblenz&Referenznummer=123K&Geburtsdatum=10.06.2003'),
})

expect(result.current.selfServiceCard).toEqual({
expirationDate: { day: 1, isoMonth: 1, isoYear: 2026 },
extensions: {
birthday: {
day: 10,
isoMonth: 6,
isoYear: 2003,
},
koblenzReferenceNumber: '123K',
},
fullName: 'Karla Koblenz',
id: expect.any(Number),
})
})
})