Skip to content

Commit

Permalink
Rewriting form data storage (#1712)
Browse files Browse the repository at this point in the history
* Adding a way to feature toggle (with hard-coded values), so that we can easily switch back and forth between implementations

* Starting implementing a compatibility, rewriting existing code where we read from the data model to use the new hook instead of the (soon to be old) redux state. I think I'm on the right path here, but there are still errors in my code right now that I don't have great solutions for. Passing the hook-state into every other saga function seems futile (I tried that), so I'm committing now to try some variations.

* Making the IAltinnWindow a global type that doesn't need to importing or casting. Renaming `global.d.ts` to `modules.d.ts`, because using imports in this file breaks TypeScript everywhere when importing module css files.

* Making the instanceId in the window object possibly undefined, as it has always been.

* Cheating a little, and setting the current form data in an object globally on the window object. This lets me rewrite parts of the form data storage system without doing it all at once, and without passing the formData (and future variables) around into every other saga action that needs to read it.

* Adding global.d.ts back to the cypress tsconfig

* Consolidating two identical types

* Adding useDebounce hook

* Using the global state most places, instead of the state in redux that should only be accessed directly from the relevant sagas

* Refactoring createFormDataRequest() function, making it exportable for re-use in new functionality

* useDelayedSavedState is built-in to the new solution, so there's no need for it when it is switched on. Making a dummy.

* Checking in my current changes. These are somewhat working, but much is left to implement. Committing them now to avoid having these huge commits in the future.

* Adding better types, and removing casting to any

* Stricter types

* Refactoring even more to allow for re-use of each part of these functions

* Further developments, trying to get legacy rules to work, but currently everything re-renders and causes infinite loops. Need to rethink the structure here, because this became a hook-mess pretty quickly.

* Fixing unit tests

* WIP. Now adding a state machine/large reducer that handles the state changes. Aaaand we're back to where we started with Redux, I suppose. Hoping this works better to avoid the mess, and figuring out why I get an infinite loop of changes (although it isn't working quite yet).

* Finally got the infinite loop thing to stop, it seems. Still think that making useStateDeepEqual to fix this was hacky, because the root problem is that some state seems to change and make everything fail for some reason, but haven't gotten to the bottom of it quite yet. Happy that it works better now! Using immer for the reducer as well, as this makes things much easier to work with.

* Moving the debounced state closer to the reducer, extracting performSave(), trying to get state changes down to a minimum

* Moving the debounce logic closer to the reducer, making it possible to 'freeze' debounced data right away after fetching the data

* Implementing a queue, solving most needless state changes

* Implementing rule-runner at freeze-point, handling changed fields

* Adding more data model fetch hooks, trying to avoid unnecessary re-renders by deep-comparing and memoizing

* Using the freshest possible data in the expression playground, and also JSON formatting the output so that null actually shows up as null

* Trying to use current formData, and cheating a bit to avoid all the type problems with introducing other types than strings

* Allowing undefined as data model bindings (returns empty object)

* Updating yarn.lock after merge from main

* Rewriting to use new feature toggle functionality

* Some fixes after merge from main

* More cleanup, aiming to make this a breaking change

* Removing todo file I mistakenly committed, and removing now-unused type

* Installing use-immer again, after merge from main removed it

* Fixing ExprContext error after merge from main

* Starting to remove the legacy formData functionality. This creates lots of errors currently, but I'll clean those up later.

* Low-hanging fruit when cleaning up after merge from main and previous typescript errors: Removing deprecated/compatibility solution (storing the form data in the window object to make it easy for sagas to reach), allowing for formData to be injected into unit tests, etc.

* Removing dead/commented out code

* Moving some code around, placing it where it belongs

* Removing the unused altinnStudioTheme

* Cleaning up some wrong theme usage, rewriting logo to not use css filtering to recolor the logo

* Rewriting all the queries that ran in App.tsx to providers

* Removing most error states, starting to rewrite error catching and outputting to use DisplayError.tsx. Committing this knowing that much of the code does not currently pass type-checks.

* More rewriting. Starting to think I should restructure the createContext functions

* More rewriting

* Cleaning up after merge

* Making providers for KeepAlive and WindowTitle, so that App.tsx can be just a router

* More cleanup, trying to pull the complexity out of Entrypoint.tsx and putting what I can into a router

* Rewriting app texts from redux selectors to hooks, fixing cyclic import problems with query providers

* Fixing returnInstanceMetaDataObject(), now called getSummaryDataObject(), after implementing useAppReceiver()

* Rewriting to use createStrictQueryContext() a few places

* Rewriting createStrictContext/createLaxContext and createStrictQueryContext/createLaxQueryContext into unified (and simplified + improved) variants

* Attempting a rewrite of party-related states into PartiesProvider and ValidPartyProvider. There's still some inconsistencies around having a valid party. The InstantiationButton (for example) does not check to see if the current party is valid to instantiate before performing instantiation.

* Fixing unit tests, rendering the default logo when application metadata is not yet fetched, mocking fetchTextResources() most places

* Refactoring the Header component, and partly the PresentationComponent, so that they work before app texts have been fetched

* Moving mock generators

* Fixing the rest of the unit tests

* Making sure we instantiate when there are no active instances, preventing runaway party validation

* Fixing header font color

* Removing layout-sets.ts, v4 only supports apps with layout-sets now

* Updating the page-order-with-dynamics.ts test. The app is no longer so slow that this request halts, so the test should no longer assume it

* Re-introducing the fix for re-fetching languages and injecting them into redux

* Removing duplicate import after merge from main

* The org name should be displayed in the app header by default

* Moving language and text-resource related code to src/features/language (this is most of the move, not all)

* Fixing up party selection and related code.
- Removing ValidPartyProvider.tsx, as validating the current party is done implicitly by checking if the party is in the list of valid parties we already fetch. We must have a valid party to proceed to instantiation.
- Introducing a LanguageProvider that keeps tabs on which language is currently selected in the app. Loading a Profile will automatically select the language given in the profile.
- Renaming reportee-selection.ts to party-selection.ts and adjusting the tests after minor (non-functional) changes

* Removing the language state properly, moving it into LanguageProvider

* Various cleanup

* Mending tests

* Moving LegacyRoutes back in to the regular router

* Resolving TODO in submitFormDataSagas

* Fixing a crash in formatting.ts because of an untyped value (any)

* Fixes after merge from main

* Allowing for multiple date formats. Potential bug reported here: Altinn/codelists-lib-dotnet#27

* Disabling the custom receipt test, as it broke (again)

* Removing debug statement

* Running eslint --fix

* Fixing the party selection test to also work on tt02

* Increasing the default timeouts, tests were timing out on github

* Restructuring the login and party-selection code in the double-signing.ts test, to make it work again on tt02 as well

* Fixing the broken SVG re-coloring

* Using receipt.receipt as the default header, not receipt.title

* Adjusting the code to compare SVGs

* Fixing DevTools

* Rewriting getAllowAnonymous to be a hook instead of a selector. Now it always returns boolean, because we can assume the layout sets and application metadata to be fetched.

* Setting anonymous/partyId in redux while we're still limited by sagas

* Fixing a bunch of errors after merging from main

* Fixing more errors after merging from main

* Cleaning up after merge

* Quick-and-dirty fixes to reduce the list of typescript errors

* Commenting out and deleting more code to get rid of all errors

* Renaming and moving hierarchy/nodes/ExprContext->NodesContext

* Moving DevTools, making the app render properly (even when we don't currently have the repeatingGroups state)

* Getting rid of top-level state changes that mess up form data saving

* Fixes after merge from main

* Updating code generation paths

* Removing multiPartSave feature toggle - backend will never expose it, but it will be available from 8.0.0 (which is the minimum we'll require)

* Removing flat data from the inner storage, cleaning up a bit

* Debugging re-renders by using dummy data a few places temporarily

* Moving LayoutNode and related files back to their original location. This caused a massive cyclic import problem on main, and it was always a big risk having this move operation in this branch and mixing it in among all the other changes here.

* Using the new form data in components, simplifying GenericComponent and preventing it from re-rendering by extracting legend/label/description

* Always returning string, even if form data is undefined (making sure not to default to uncontrolled form components), providing test utilities so that unit tests will still work.

* Fixing AddressComponent.test.tsx. Not all the tests inside are passing yet

* Fixing type errors

* Fixing the rest of the tests, no more typescript errors. Some tests are failing still, but mostly because of the missing support for repeating groups

* Started testing out useContextSelector() to prevent unnecessary renders. Made hooks for getting the current URL and using that when saving the data model.

* Extracting out parts of renderWithProviders.tsx so that it's possible to use the same mocking tools to bootstrap a fake subset of mocked apps that can run in a browser

* Making a test that documents problems causing re-rendering all components when a single leaf node in the form data changes

* Removing use-context-selector, will replace this all with zustand + immer

* Rewriting it all to use zustand + immer. Now finally the test passes, and nothing is re-rendered when state is changed deep inside objects

* Typing the return value from form saving, getting rid of historical baggage we no longer need

* Implementing variable debounce timeout, as implemented by saveWhileTyping previously

* Documenting that the saveWhileTyping property can only be a number now

* Fixing some brokenness in navigation that I observed after merging from main. The navigation in ProcessWrapperWrapper caused an infinite redirect loop, as it just appends to the current URL. Also, moving providers to more logical places, thus also getting rid of FormData.tsx, as it's no longer needed when the state we need to switch between formData providers are in the URL already.

* Fixing the test runner again so that useLayouts() still work, and nodes are generated again. Making this easier to notice in the future by defaulting to rejecting fetchLayouts() in tests unless mocked with something.

* Implementing the multiSetFormData stuff I always wanted to have in ListComponent.tsx

* Implementing form data locking, and using it in CustomButtonComponent.tsx

* Creating the structure for a zustand-powered repeating groups context

* Adding a test to make sure that form data is saved when we navigate away in the URL/router, and implementing it in the FormDataEffects component

* Generating repeating groups state the same way we did in the saga

* Started working on ripping out the repeatingGroups state from UiConfig. When I looked into rewriting the repeating groups state to a context and replicating/re-using all the older cruft, it dawned on me that I should just use the form data to figure out the `index` (aka how many rows there are). When doing that, I can just skip passing `repeatingGroups` to the node hierarchy when generating that, and at that point there's no point in initializing the `repeatingGroups` state at all, since it will always default to `-1` for `editIndex`, etc. We can just generate states on the fly when needed (i.e. when the components render). That is, if we need to keep this state globally at all - I think we can reduce this all to some simple `useState()` values in the repeating groups component, so that it can keep track of which rows are open there. Let's start this and figure it out as we go!

* Well, that was way easier than expected! hierarchy.test.ts now passes, without using the `repeatingGroups` state at all

* Making conditionalRendering work with nodes

* Removing unused code

* Removing more unused code, cleaning up in tests

* Repeating groups are now showing up! Simplifying displayData to use the node function to get their form data

* Getting somewhere - adding a context for containing all the state and state manipulation methods in repeating groups. Reducing the number of props by a lot

* Adding a context for setting multiPage states

* Fixing tests

* Fixing some state handling to work properly, making diffModels only report on scalar values

* Using flattenObject() to fix the diffModels code instead. Removing debugging.

* Fixing minor bugs re: empty/0/null values

* Fixing unit tests

* Fixing the interdependency of the attachments and nodes contexts

* Fixing some tests, breaking lots more. Cleaning up the test framework a bit, getting rid of unmockable queries (and providing good defaults instead). This fixes the NavigationButtonsComponent.test.tsx, which was quite broken now that I started using contexts instead of redux.

* Fixing more tests. Cleaning up ReceiptContainer.tsx now that custom receipt doesn't work

* Using contexts instead of redux most places

* Splitting up AllOptionsProvider, just like AttachmentsProvider

* Making the applications load again

* Fixing more tests

* Removing lots of functionality from the AddressComponent.tsx that will be rewritten in the validation rewrite anyway, skipping more tests

* Using isLoading instead of isFetching in useGetOptions(), as we don't want the spinner/loader when re-fetching in the background

* Working around the issue where the language switcher renders the Loader and destroys state for open repeating groups, etc

* Revert "Using isLoading instead of isFetching in useGetOptions(), as we don't want the spinner/loader when re-fetching in the background"

This reverts commit afb027d.

* Re-implementing cy.changeLayout(), cleaning up stuff we no longer need in the window object

* Enabling PDF rendering again, moving it to a wrapper outside Form.tsx

* Changing the cy.dsSelect() function so that it runs multiple get() instead wrap(). This will ensure the element is re-selected, and fixes problems like 'element updated while running'

* Making ProcessNavigationContext save the latest form data before navigating away, making FD.useWaitForSave() work even without a context, fixing useWaitForState so that it doesn't need a cache key and returns immediately if state is already correct.

* Removing PageKeys. No need to pretend non-data tasks have individual pages. This caused a problem where a confirmation task without a current page would try to render <Form /> to make it navigate to the correct first page for that task, but a <Form /> cannot be loaded because FormDataWrite cannot be provided when you don't have any data model to write to. When rendering the task directly on the task route, I also think it all looks more logical. Oh, and we can't render a receipt in a stateless app - that concept does not exist (yet).

* Providing process navigation to the Confirm step

* Fixing the failing footer test, skipping a test for the Address component that will be fixed in the validation rewrite

* Adding back debouncing on blur in most components. This fixes some problems in the components.ts test. Strictly not needed, but now things work more like they used to.

* Commenting out more validation stuff

* Fixing the customButton test. The form data locking and unlocking code was not working as intended.

* Skipping some tests, re-implementing openByDefault.

* Fixing the bug mentioned in hide-row-in-group, fixing saveAndNext button in repeating groups, using useAsRefObject() to make the functions in RepeatingGroupContext re-render less often, and exposing more useful state about hidden/visible rows. Also removing the duplicate/broken useMemoDeepEqual.ts.

* Re-implementing the logic to find and focus a certain node. Re-using the logic from ErrorReport in Summary, and moving the PageNavigationContext into FormProvider, where it belongs.

* Implementing the rest of the previous functionality, and most likely some more

* Fixing opening repeating group rows for editing when clicking the 'add new' button (it now only happens if editing is allowed for that row). Adjusting the test, now that navigation from summary works the same as from ErrorReport

* Running rules after saving, as tested in rules.ts. Skipping a test in summary.ts.

* Fixing usePickFreshStrings() and implementing it without a Proxy object so that the list component cypress test works

* Commenting out broken validation tests

* Making the PDF test a bit more realistic, fixing a problem I found when doing that, commenting out a bit that was testing the address component

* Fixes after merging from main

* Fixes after sloppy fixes

* Implementing auto-save on page change, and fixing the test for it

* Fixing attachments-in-group.ts

* Using cy.waitUntil() to make the attachments-in-group.ts test more stable

* Fixing multipart-save.ts

* Fixing form saving for stateless apps

* Fixing the functionality needed for the 'prefill' test for stateless apps

* Fixes for the anonoymous.ts test, and removing some dead code

* Fixing unit tests. The List component never had onBlur debouncing before, and it looks like it debounces immediately now, so I'll remove it again.

* Updating tests. The FormData.test.tsx is using the stateless endpoint, so it's not using doPutFormData any longer.

* Fixing flakiness in mobile.ts

* Minor test warning fixes

* Cleaning up a bit

* Removing the error about non-gatekept dispatchers. Redux is going away soon anyway.

* Moving some code around to reduce the import-depth in unit tests

* Removing redux init code that causes lots of imports

* Dropping the FormDataForInfoTaskProvider for receipts. Custom receipts are not implemented now, and I'll take a chance nobody is really using this (at least our tests)

* Adding a reproduction for the bug the slower github runner found, implementing our own way to apply changes between models to work around the issue

* Cleaning up after tips from sonarcloud

* Fixing flaky test

---------

Co-authored-by: Ole Martin Handeland <[email protected]>
  • Loading branch information
olemartinorg and Ole Martin Handeland authored Dec 28, 2023
1 parent 80eeec7 commit 33bbeb8
Show file tree
Hide file tree
Showing 268 changed files with 7,340 additions and 8,971 deletions.
7 changes: 6 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@
}
],
"@typescript-eslint/consistent-type-imports": ["warn"],
"react-hooks/exhaustive-deps": ["error"],
"react-hooks/exhaustive-deps": [
"error",
{
"additionalHooks": "^(useMemoDeepEqual)$"
}
],
"prefer-template": ["warn"],
"sonarjs/no-duplicate-string": ["off"],
"sonarjs/cognitive-complexity": ["off"],
Expand Down
5 changes: 2 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ const env = require('dotenv').config();

const enableJestPreview = env.parsed?.JEST_PREVIEW === 'true';

/** @type {import('jest').Config} */
/** @type {import('ts-jest').JestConfigWithTsJest} */
const config = {
preset: 'ts-jest',
transform: {
'\\.(js|ts|tsx)$': ['ts-jest', { isolatedModules: true }],
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/test/jestTools/transformFile.js',

...(enableJestPreview && {
'\\.(s?css|less)$': 'jest-preview/transforms/css',
// '^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': 'jest-preview/transforms/file',
}),
...(!enableJestPreview && {
'\\.(s?css|less)$': '<rootDir>/src/test/jestTools/transformCss.js',
Expand All @@ -23,7 +23,6 @@ const config = {
moduleNameMapper: {
'^src/(.*)$': '<rootDir>/src/$1',
'^schemas/(.*)$': '<rootDir>/schemas/$1',
// '^uuid$': '<rootDir>/node_modules/uuid/dist/index.js',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
testRegex: '\\.test\\.(ts|tsx|js|jsx)$',
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@
"redux-saga": "1.2.3",
"reselect": "4.1.8",
"typescript": "5.3.2",
"uuid": "9.0.1"
"uuid": "9.0.1",
"zustand": "^4.4.7"
},
"packageManager": "[email protected]",
"lint-staged": {
Expand Down
150 changes: 81 additions & 69 deletions src/__mocks__/getApplicationMetadataMock.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,87 @@
import type { IApplicationMetadata } from 'src/features/applicationMetadata';

export const getApplicationMetadataMock = (overrides: Partial<IApplicationMetadata> = {}): IApplicationMetadata => ({
id: 'mockOrg/test-app',
org: 'mockOrg',
title: {
nb: 'Test App',
},
autoDeleteOnProcessEnd: false,
dataTypes: [
{
id: 'test-data-model',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema',
},
taskId: 'Task_1',
maxCount: 1,
minCount: 1,
},
{
id: 'ref-data-as-pdf',
allowedContentTypes: ['application/pdf'],
maxCount: 0,
minCount: 0,
},
{
id: 'test-data-type-1',
allowedContentTypes: ['application/pdf'],
maxCount: 5,
minCount: 0,
export const getApplicationMetadataMock = (
overrides: Partial<IApplicationMetadata> | ((application: IApplicationMetadata) => void) = {},
): IApplicationMetadata => {
const out: IApplicationMetadata = {
id: 'mockOrg/test-app',
org: 'mockOrg',
title: {
nb: 'Test App',
},
{
id: 'test-data-type-2',
allowedContentTypes: ['application/pdf'],
maxCount: 2,
minCount: 0,
},
{
id: 'stateless',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema2',
autoDeleteOnProcessEnd: false,
dataTypes: [
{
id: 'test-data-model',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema',
},
taskId: 'Task_1',
maxCount: 1,
minCount: 1,
},
taskId: 'Task_0',
maxCount: 1,
minCount: 1,
},
{
id: 'stateless-anon',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema3',
allowAnonymousOnStateless: true,
{
id: 'ref-data-as-pdf',
allowedContentTypes: ['application/pdf'],
maxCount: 0,
minCount: 0,
},
{
id: 'test-data-type-1',
allowedContentTypes: ['application/pdf'],
maxCount: 5,
minCount: 0,
},
taskId: 'Task_0',
maxCount: 1,
minCount: 1,
{
id: 'test-data-type-2',
allowedContentTypes: ['application/pdf'],
maxCount: 2,
minCount: 0,
},
{
id: 'stateless',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema2',
},
taskId: 'Task_0',
maxCount: 1,
minCount: 1,
},
{
id: 'stateless-anon',
allowedContentTypes: ['application/xml'],
appLogic: {
autoCreate: true,
classRef: 'Altinn.App.Models.Skjema3',
allowAnonymousOnStateless: true,
},
taskId: 'Task_0',
maxCount: 1,
minCount: 1,
},
],
partyTypesAllowed: {
bankruptcyEstate: false,
organisation: false,
person: true,
subUnit: false,
},
],
partyTypesAllowed: {
bankruptcyEstate: false,
organisation: false,
person: true,
subUnit: false,
},
created: '2020-06-29T08:47:12.425551Z',
createdBy: 'test testesen',
lastChanged: '2020-06-29T08:47:12.4255537Z',
lastChangedBy: 'test testesen',
...overrides,
});
created: '2020-06-29T08:47:12.425551Z',
createdBy: 'test testesen',
lastChanged: '2020-06-29T08:47:12.4255537Z',
lastChangedBy: 'test testesen',
...overrides,
};

if (typeof overrides === 'function') {
overrides(out);
} else if (overrides && Object.keys(overrides).length > 0) {
Object.assign(out, overrides);
}

return out;
};
14 changes: 14 additions & 0 deletions src/__mocks__/getFormDataMockForRepGroup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function getFormDataMockForRepGroup() {
return {
someGroup: [
{
valueField: 'Value for first',
labelField: 'Label for first',
},
{
valueField: 'Value for second',
labelField: 'Label for second',
},
],
};
}
21 changes: 0 additions & 21 deletions src/__mocks__/getFormDataStateMock.ts

This file was deleted.

28 changes: 11 additions & 17 deletions src/__mocks__/getFormLayoutGroupMock.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import type { CompGroupRepeatingExternal } from 'src/layout/Group/config.generated';

export function getFormLayoutGroupMock(
export const getFormLayoutGroupMock = (
customMock?: Partial<CompGroupRepeatingExternal>,
children?: string[],
): CompGroupRepeatingExternal {
const mockLayoutGroup = {
id: 'container-closed-id',
type: 'Group',
children: children || ['field1', 'field2', 'field3', 'field4'],
maxCount: 8,
dataModelBindings: {
group: 'some-group',
},
} as CompGroupRepeatingExternal;
return {
...mockLayoutGroup,
...customMock,
};
}
): CompGroupRepeatingExternal => ({
id: 'container-closed-id',
type: 'Group',
children: ['field1', 'field2', 'field3', 'field4'],
maxCount: 8,
dataModelBindings: {
group: 'some-group',
},
...customMock,
});
9 changes: 7 additions & 2 deletions src/__mocks__/getInstanceDataMock.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { IInstance } from 'src/types/shared';

export function getInstanceDataMock(): IInstance {
return {
export function getInstanceDataMock(mutate?: (data: IInstance) => void): IInstance {
const out: IInstance = {
instanceOwner: {
partyId: '12345',
personNumber: '01017512345',
Expand Down Expand Up @@ -57,4 +57,9 @@ export function getInstanceDataMock(): IInstance {
status: null,
title: null,
};

if (mutate) {
mutate(out);
}
return out;
}
27 changes: 13 additions & 14 deletions src/__mocks__/getMultiPageGroupMock.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import type { CompGroupRepeatingExternal } from 'src/layout/Group/config.generated';

export function getMultiPageGroupMock(id = 'multipageGroup'): CompGroupRepeatingExternal {
return {
type: 'Group',
id,
dataModelBindings: {
group: 'multipageGroup',
},
maxCount: 2,
edit: {
multiPage: true,
},
children: ['FormLayout:field1', 'FormLayout:field2', 'FormLayout:field3'],
};
}
export const getMultiPageGroupMock = (overrides: Partial<CompGroupRepeatingExternal>): CompGroupRepeatingExternal => ({
id: 'myMultiPageGroup',
type: 'Group',
dataModelBindings: {
group: 'multipageGroup',
},
maxCount: 2,
edit: {
multiPage: true,
},
children: ['FormLayout:field1', 'FormLayout:field2', 'FormLayout:field3'],
...overrides,
});
10 changes: 8 additions & 2 deletions src/__mocks__/getProcessDataMock.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { IProcess } from 'src/types/shared';

export function getProcessDataMock(): IProcess {
return {
export function getProcessDataMock(mutate?: (process: IProcess) => void): IProcess {
const out: IProcess = {
started: '2020-01-01',
startEvent: null,
currentTask: {
Expand All @@ -16,4 +16,10 @@ export function getProcessDataMock(): IProcess {
ended: null,
endEvent: null,
};

if (mutate) {
mutate(out);
}

return out;
}
29 changes: 15 additions & 14 deletions src/__mocks__/getUiConfigStateMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,21 @@ export const getUiConfigStateMock = (customStates?: Partial<IUiConfig>): IUiConf
order: ['FormLayout'],
},
hiddenFields: [],
repeatingGroups: {
group: {
index: 1,
dataModelBinding: 'someGroup',
},
referencedGroup: {
index: 1,
dataModelBinding: 'referencedGroup',
},
testGroupId: {
index: 1,
dataModelBinding: 'Group',
},
},
// TODO: Recreate these mocks somewhere else
// repeatingGroups: {
// group: {
// index: 1,
// dataModelBinding: 'someGroup',
// },
// referencedGroup: {
// index: 1,
// dataModelBinding: 'referencedGroup',
// },
// testGroupId: {
// index: 1,
// dataModelBinding: 'Group',
// },
// },
currentView: 'FormLayout',
excludePageFromPdf: [],
excludeComponentFromPdf: [],
Expand Down
Loading

0 comments on commit 33bbeb8

Please sign in to comment.