Skip to content

Strict null-checks #597

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

Merged
merged 8 commits into from
Nov 2, 2022
Merged
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
18 changes: 9 additions & 9 deletions src/altinn-app-frontend/__mocks__/initialStateMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export function getInitialStateMock(
error: null,
},
attachments: {
attachments: null,
attachments: {},
},
formData: getFormDataStateMock(),
formDataModel: {
error: null,
schemas: null,
schemas: {},
},
formDynamics: {
apis: null,
Expand All @@ -35,7 +35,7 @@ export function getInitialStateMock(
error: null,
fetched: false,
fetching: false,
model: null,
model: [],
},
formValidations: {
validations: {},
Expand All @@ -47,7 +47,7 @@ export function getInitialStateMock(
instantiation: {
error: null,
instanceId: null,
instantiating: null,
instantiating: false,
},
isLoading: {
dataTask: false,
Expand Down Expand Up @@ -86,11 +86,11 @@ export function getInitialStateMock(
},
profile: getProfileStateMock(),
queue: {
appTask: null,
dataTask: null,
infoTask: null,
stateless: null,
userTask: null,
appTask: { error: null, isDone: null },
dataTask: { error: null, isDone: null },
infoTask: { error: null, isDone: null },
stateless: { error: null, isDone: null },
userTask: { error: null, isDone: null },
},
textResources: {
resources: [
Expand Down
3 changes: 1 addition & 2 deletions src/altinn-app-frontend/__mocks__/instanceDataStateMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export function getInstanceDataStateMock(
instanceOwner: {
partyId: '12345',
personNumber: '01017512345',
organisationNumber: null,
},
appId: 'mockOrg/mockApp',
created: new Date('2020-01-01').toISOString(),
Expand Down Expand Up @@ -55,7 +54,7 @@ export function getInstanceDataStateMock(
},
],
id: '91cefc5e-c47b-40ff-a8a4-05971205f783',
instanceState: null,
instanceState: undefined,
lastChanged: new Date('2020-01-01').toISOString(),
org: 'mockOrg',
process: {
Expand Down
4 changes: 2 additions & 2 deletions src/altinn-app-frontend/__mocks__/partyMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export const partyMock: IParty = {
ssn: '01017512345',
partyTypeName: null,
orgNumber: null,
unitType: null,
unitType: undefined,
isDeleted: false,
onlyHierarchyElementWithNoAccess: false,
childParties: null,
childParties: undefined,
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ export const statelessAndAllowAnonymousMock = (
) => {
const initialState = getInitialStateMock();
const initialAppMetadata: IApplicationMetadata = {
...initialState.applicationMetadata.applicationMetadata,
...(initialState.applicationMetadata
.applicationMetadata as IApplicationMetadata),
onEntry: {
show: 'stateless',
},
};
initialAppMetadata.dataTypes[0].appLogic.allowAnonymousOnStateless =
allowAnonymous;
if (initialAppMetadata.dataTypes[0].appLogic) {
initialAppMetadata.dataTypes[0].appLogic.allowAnonymousOnStateless =
allowAnonymous;
}
const mockInitialState: IRuntimeState = {
...initialState,
applicationMetadata: {
Expand Down
2 changes: 1 addition & 1 deletion src/altinn-app-frontend/__mocks__/uiConfigStateMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const getUiConfigStateMock = (
dataModelBinding: 'Group',
},
},
fileUploadersWithTag: null,
fileUploadersWithTag: undefined,
currentView: 'FormLayout',
navigationConfig: {},
...customStates,
Expand Down
4 changes: 2 additions & 2 deletions src/altinn-app-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"test": "jest",
"test:watch": "jest --watch",
"test:watchall": "jest --watchAll",
"tsc": "tsc --noEmit --skipLibCheck",
"tsc:watch": "tsc --watch --noEmit --skipLibCheck",
"tsc": "tsc",
"tsc:watch": "tsc --watch",
"clean": "rimraf dist compiled",
"webpack-watch": "cross-env NODE_ENV=development webpack --mode=development --config webpack.config.development.js --watch --progress",
"styleguidist:run": "yarn dlx styleguidist server",
Expand Down
2 changes: 1 addition & 1 deletion src/altinn-app-frontend/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('App', () => {
anonymousSelector,
'makeGetAllowAnonymousSelector',
);
let allowAnonymous = undefined;
let allowAnonymous: boolean | undefined = undefined;
const getAllowAnonymous = () => allowAnonymous;
beforeEach(() => {
allowAnonymous = undefined;
Expand Down
4 changes: 3 additions & 1 deletion src/altinn-app-frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ export const App = () => {
get(refreshJwtTokenUrl).catch((err) => {
// Most likely the user has an expired token, so we redirect to the login-page
try {
window.location.href = getEnvironmentLoginUrl(appOidcProvider);
window.location.href = getEnvironmentLoginUrl(
appOidcProvider || null,
);
} catch (error) {
console.error(err, error);
}
Expand Down
10 changes: 8 additions & 2 deletions src/altinn-app-frontend/src/components/GenericComponent.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import React from 'react';

import { getFormDataStateMock, getFormLayoutStateMock } from '__mocks__/mocks';
import {
getFormDataStateMock,
getFormLayoutStateMock,
getInitialStateMock,
} from '__mocks__/mocks';
import { screen } from '@testing-library/react';
import { renderWithProviders } from 'testUtils';
import { mockComponentProps, renderWithProviders } from 'testUtils';

import { GenericComponent } from 'src/components/GenericComponent';
import type { IActualGenericComponentProps } from 'src/components/GenericComponent';

const render = (props: Partial<IActualGenericComponentProps<any>> = {}) => {
const allProps: IActualGenericComponentProps<'Input'> = {
...mockComponentProps,
id: 'mockId',
type: 'Input' as any,
textResourceBindings: {},
Expand Down Expand Up @@ -57,6 +62,7 @@ const render = (props: Partial<IActualGenericComponentProps<any>> = {}) => {

renderWithProviders(<GenericComponent {...allProps} />, {
preloadedState: {
...getInitialStateMock(),
formLayout,
formData,
},
Expand Down
26 changes: 17 additions & 9 deletions src/altinn-app-frontend/src/components/GenericComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function GenericComponent<Type extends ComponentExceptGroup>(
const { id, ...passThroughProps } = props;
const dispatch = useAppDispatch();
const classes = useStyles(props);
const gridRef = React.useRef<HTMLDivElement>();
const gridRef = React.useRef<HTMLDivElement>(null);
const GetHiddenSelector = makeGetHidden();
const GetFocusSelector = makeGetFocus();
const [hasValidationMessages, setHasValidationMessages] =
Expand Down Expand Up @@ -181,7 +181,7 @@ export function GenericComponent<Type extends ComponentExceptGroup>(
}
}, [shouldFocus, hidden, dispatch]);

if (hidden) {
if (hidden || !language) {
return null;
}

Expand Down Expand Up @@ -414,15 +414,23 @@ const RenderLabelScoped = (props: IRenderLabelProps) => {
};

const gridToHiddenProps = (
labelGrid: IGridStyling,
labelGrid: IGridStyling | undefined,
classes: ReturnType<typeof useStyles>,
) => {
if (!labelGrid) return undefined;
if (!labelGrid) {
return undefined;
}

return {
[classes.xs]: labelGrid.xs > 0 && labelGrid.xs < 12,
[classes.sm]: labelGrid.sm > 0 && labelGrid.sm < 12,
[classes.md]: labelGrid.md > 0 && labelGrid.md < 12,
[classes.lg]: labelGrid.lg > 0 && labelGrid.lg < 12,
[classes.xl]: labelGrid.xl > 0 && labelGrid.xl < 12,
[classes.xs]:
labelGrid.xs !== undefined && labelGrid.xs > 0 && labelGrid.xs < 12,
[classes.sm]:
labelGrid.sm !== undefined && labelGrid.sm > 0 && labelGrid.sm < 12,
[classes.md]:
labelGrid.md !== undefined && labelGrid.md > 0 && labelGrid.md < 12,
[classes.lg]:
labelGrid.lg !== undefined && labelGrid.lg > 0 && labelGrid.lg < 12,
[classes.xl]:
labelGrid.xl !== undefined && labelGrid.xl > 0 && labelGrid.xl < 12,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { fireEvent, render as rtlRender, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import mockAxios from 'jest-mock-axios';
import configureStore from 'redux-mock-store';
import { mockComponentProps } from 'testUtils';

import { AddressComponent } from 'src/components/advanced/AddressComponent';
import type { IAddressComponentProps } from 'src/components/advanced/AddressComponent';
Expand All @@ -29,24 +30,17 @@ const render = (props: Partial<IAddressComponentProps> = {}) => {
};

const allProps: IAddressComponentProps = {
id: 'id',
...mockComponentProps,
formData: {
address: 'adresse 1',
},
handleDataChange: () => '',
getTextResource: () => 'test',
isValid: true,
simplified: true,
dataModelBindings: {},
componentValidations: {
zipCode: null,
houseNumber: null,
},
language: mockLanguage,
readOnly: false,
required: false,
textResourceBindings: {},
...({} as IAddressComponentProps),
...props,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,32 +93,29 @@ export function AddressComponent({
saveWhileTyping,
);

const [validations, setValidations] = React.useState({} as any);
const prevZipCode = React.useRef(null);
const hasFetchedPostPlace = React.useRef(false);
const [validations, setValidations] =
React.useState<IAddressValidationErrors>({});
const prevZipCode = React.useRef<string | undefined>(undefined);
const hasFetchedPostPlace = React.useRef<boolean>(false);

const validate = React.useCallback(() => {
const validationErrors: IAddressValidationErrors = {
zipCode: null,
houseNumber: null,
postPlace: null,
};
const validationErrors: IAddressValidationErrors = {};
if (zipCode && !zipCode.match(/^\d{4}$/)) {
validationErrors.zipCode = getLanguageFromKey(
'address_component.validation_error_zipcode',
language,
);
setPostPlace('');
} else {
validationErrors.zipCode = null;
delete validationErrors.zipCode;
}
if (houseNumber && !houseNumber.match(/^[a-z,A-Z]{1}\d{4}$/)) {
validationErrors.houseNumber = getLanguageFromKey(
'address_component.validation_error_house_number',
language,
);
} else {
validationErrors.houseNumber = null;
delete validationErrors.houseNumber;
}
return validationErrors;
}, [houseNumber, language, zipCode, setPostPlace]);
Expand Down Expand Up @@ -170,7 +167,7 @@ export function AddressComponent({
);
if (response.valid) {
setPostPlace(response.result);
setValidations({ ...validations, zipCode: null });
setValidations({ ...validations, zipCode: undefined });
onSaveField(AddressKeys.postPlace, response.result);
} else {
const errorMessage = getLanguageFromKey(
Expand Down Expand Up @@ -238,10 +235,7 @@ export function AddressComponent({
};

const joinValidationMessages = (): IComponentValidations => {
let validationMessages = componentValidations;
if (!validationMessages) {
validationMessages = {};
}
let validationMessages = componentValidations || {};

Object.keys(AddressKeys).forEach((fieldKey: string) => {
if (!validationMessages[fieldKey]) {
Expand All @@ -256,13 +250,13 @@ export function AddressComponent({
});

Object.keys(validations).forEach((fieldKey: string) => {
if (validations[fieldKey]) {
if (validationMessages[fieldKey]) {
const validationMessage = validations[fieldKey];
const match =
validationMessages[fieldKey].errors.indexOf(validationMessage) > -1;
const source = validations[fieldKey];
if (source) {
const target = validationMessages[fieldKey];
if (target) {
const match = target.errors && target.errors.indexOf(source) > -1;
if (!match) {
validationMessages[fieldKey].errors.push(validations[fieldKey]);
validationMessages[fieldKey]?.errors?.push(validations[fieldKey]);
}
} else {
validationMessages = {
Expand All @@ -272,7 +266,7 @@ export function AddressComponent({
warnings: [],
},
};
validationMessages[fieldKey].errors = [validations[fieldKey]];
(validationMessages[fieldKey] || {}).errors = [validations[fieldKey]];
}
}
});
Expand All @@ -298,7 +292,7 @@ export function AddressComponent({
/>
<TextField
id={`address_address_${id}`}
isValid={allValidations.address.errors.length === 0}
isValid={allValidations.address?.errors?.length === 0}
value={address}
onChange={updateField.bind(null, AddressKeys.address, false)}
onBlur={updateField.bind(null, AddressKeys.address, true)}
Expand Down Expand Up @@ -326,7 +320,7 @@ export function AddressComponent({
/>
<TextField
id={`address_care_of_${id}`}
isValid={allValidations.careOf.errors.length === 0}
isValid={allValidations.careOf?.errors?.length === 0}
value={careOf}
onChange={updateField.bind(null, AddressKeys.careOf, false)}
onBlur={updateField.bind(null, AddressKeys.careOf, true)}
Expand Down Expand Up @@ -355,7 +349,7 @@ export function AddressComponent({
<div className={'address-component-small-inputs'}>
<TextField
id={`address_zip_code_${id}`}
isValid={allValidations.zipCode.errors.length === 0}
isValid={allValidations.zipCode?.errors?.length === 0}
value={zipCode}
onChange={updateField.bind(null, AddressKeys.zipCode, false)}
onBlur={updateField.bind(null, AddressKeys.zipCode, true)}
Expand Down Expand Up @@ -384,7 +378,7 @@ export function AddressComponent({
/>
<TextField
id={`address_post_place_${id}`}
isValid={allValidations.postPlace.errors.length === 0}
isValid={allValidations.postPlace?.errors?.length === 0}
value={postPlace}
readOnly={true}
required={required}
Expand Down Expand Up @@ -417,7 +411,7 @@ export function AddressComponent({
<div className={'address-component-small-inputs'}>
<TextField
id={`address_house_number_${id}`}
isValid={allValidations.houseNumber.errors.length === 0}
isValid={allValidations.houseNumber?.errors?.length === 0}
value={houseNumber}
onChange={updateField.bind(null, AddressKeys.houseNumber, false)}
onBlur={updateField.bind(null, AddressKeys.houseNumber, true)}
Expand Down
Loading