From 7d386dc118e76188e619c3a4d41d35a4aca9d123 Mon Sep 17 00:00:00 2001 From: Dave Roberts <145559566+droberts-ctrlo@users.noreply.github.com> Date: Thu, 26 Oct 2023 11:31:26 +0100 Subject: [PATCH] Adding unittests (#258) * Schema Updates Updated to add Report table * Table view in progress and controller changes * Jest package changes (#6) * Updated Schema (correctly this time) Still need to add other files and entries as per user changes as noted in email from Andy previously * Stopped being a chump Worked out field display wasn't working because I was being dumb - will now work on displaying ID, User and Created By fields correctly. * Working on add Add endpoint created - need to work on how and what to include in the edit (checkboxes to view all fields in table) Possibly see about moving common code into parent sub. * Edited formatting on template to make it easier to read * Schema changes for use of report by multiple groups * Further changes to schema It was decided the permission to view PDF would be enough for all reports rather than just allowing for the user to create reports for specific groups (Discussion with JH - 23/10/23) Files do not contain "fixes" as required for schema generation - will add when stage complete and schema finalised. * Create report button added Also fixed minor typo within Markdown component definition in site.js * Minor fieldset changes for functionality Have added "required" attribute to allow for adding of asterisk * Report view changes * Routes and controller work for reporting Purely staging in order to ensure all file changes are backed up. * Unit test fixes Have made unit testing work - "test" folder contains stubs or full implementations for use within testing (as babel is used and doesn't "like" certain paths because of exclusion rules, causing tests to fail) - will explain if required in face-to-face meeting this week with AB * Undid accidental merge * Reset files for user edit * ESLint corrected * ESLint Corrected (Again) * Updated gads.pm * Updated user.pm * Updated user.pm (again) * Added readme for tests folder --- jest.config.js | 202 +++++++++++++++++++++ package.json | 5 + src/frontend/test/README.md | 3 + src/frontend/test/component.js | 100 +++++++++++ src/frontend/test/logging.js | 34 ++++ src/frontend/test/validation.js | 300 ++++++++++++++++++++++++++++++++ tsconfig.json | 9 +- webpack.config.js | 4 +- 8 files changed, 653 insertions(+), 4 deletions(-) create mode 100644 jest.config.js create mode 100644 src/frontend/test/README.md create mode 100644 src/frontend/test/component.js create mode 100644 src/frontend/test/logging.js create mode 100644 src/frontend/test/validation.js diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 000000000..2fddcc075 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,202 @@ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ + +/** @type {import('jest').Config} */ +const config = { + // All imported modules in your tests should be mocked automatically + // automock: false, + + // Stop running tests after `n` failures + // bail: 0, + + // The directory where Jest should store its cached dependency information + // cacheDirectory: "/tmp/jest_rt", + + // Automatically clear mock calls, instances, contexts and results before every test + // clearMocks: false, + + // Indicates whether the coverage information should be collected while executing the test + // collectCoverage: false, + + // An array of glob patterns indicating a set of files for which coverage information should be collected + // collectCoverageFrom: undefined, + + // The directory where Jest should output its coverage files + // coverageDirectory: undefined, + + // An array of regexp pattern strings used to skip coverage collection + // coveragePathIgnorePatterns: [ + // "/node_modules/" + // ], + + // Indicates which provider should be used to instrument code for coverage + // coverageProvider: "babel", + + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], + + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: undefined, + + // A path to a custom dependency extractor + // dependencyExtractor: undefined, + + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, + + // The default configuration for fake timers + // fakeTimers: { + // "enableGlobally": false + // }, + + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], + + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: undefined, + + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: undefined, + + // A set of global variables that need to be available in all test environments + // globals: {}, + + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", + + // An array of directory names to be searched recursively up from the requiring module's location + // moduleDirectories: [ + // "node_modules" + // ], + + // An array of file extensions your modules use + // moduleFileExtensions: [ + // "js", + // "mjs", + // "cjs", + // "jsx", + // "ts", + // "tsx", + // "json", + // "node" + // ], + + // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module + moduleNameMapper: { + "^component$": "/src/frontend/test/component", + "^validation$": "/src/frontend/test/validation", + "^logging$": "/src/frontend/test/logging", + }, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + // modulePathIgnorePatterns: [], + + // Activates notifications for test results + // notify: false, + + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", + + // A preset that is used as a base for Jest's configuration + // preset: undefined, + + // Run tests from one or more projects + // projects: undefined, + + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, + + // Automatically reset mock state before every test + // resetMocks: false, + + // Reset the module registry before running each individual test + // resetModules: false, + + // A path to a custom resolver + // resolver: undefined, + + // Automatically restore mock state and implementation before every test + // restoreMocks: false, + + // The root directory that Jest should scan for tests and modules within + // rootDir: undefined, + + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], + + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", + + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + // setupFilesAfterEnv: [], + + // The number of seconds after which a test is considered as slow and reported as such in the results. + // slowTestThreshold: 5, + + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], + + // The test environment that will be used for testing + testEnvironment: "jsdom", + + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, + + // Adds a location field to test results + // testLocationInResults: false, + + // The glob patterns Jest uses to detect test files + // testMatch: [ + // "**/__tests__/**/*.[jt]s?(x)", + // "**/?(*.)+(spec|test).[tj]s?(x)" + // ], + + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "/node_modules/" + // ], + + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], + + // This option allows the use of a custom results processor + // testResultsProcessor: undefined, + + // This option allows use of a custom test runner + // testRunner: "jest-circus/runner", + + // A map from regular expressions to paths to transformers + // transform: undefined, + + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // "/node_modules/", + // "\\.pnp\\.[^\\/]+$" + // ], + + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, + + // Indicates whether each individual test should be reported during the run + // verbose: undefined, + + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], + + // Whether to use watchman for file crawling + // watchman: true, +}; + +module.exports = config; diff --git a/package.json b/package.json index 7dc58ed18..678ea277d 100644 --- a/package.json +++ b/package.json @@ -50,14 +50,18 @@ }, "devDependencies": { "@babel/core": "^7.14.6", + "@babel/plugin-transform-react-jsx": "^7.22.15", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.16.7", "@babel/preset-typescript": "^7.16.7", "@babel/runtime-corejs3": "^7.14.7", + "@types/jest": "^29.5.6", + "@types/jquery": "^3.5.24", "@types/react": "^17.0.41", "@types/react-dom": "^17.0.14", "@types/react-grid-layout": "^1.3.2", "@webpack-cli/serve": "^2.0.1", + "babel-jest": "^29.7.0", "babel-loader": "^8.2.2", "buffer": "^6.0.3", "clean-webpack-plugin": "^4.0.0", @@ -69,6 +73,7 @@ "eslint-plugin-jsdoc": "^46.8.1", "eslint-plugin-prettier": "^5.0.0", "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", "jshint": "^2.11.0", "mini-css-extract-plugin": "^2.7.2", "npm-watch": "^0.6.0", diff --git a/src/frontend/test/README.md b/src/frontend/test/README.md new file mode 100644 index 000000000..d27383a24 --- /dev/null +++ b/src/frontend/test/README.md @@ -0,0 +1,3 @@ +# Test folder +This folder contains stubs and/or copies of functionality used within the system. It is felt that (at this time), this is a "necessary" thing for unit testing - this is here because Jest (the JS unit testing framework) uses Babel behind the scenes; the `/src/frontend/lib` directory is ignored by Babel - when this ignore is removed (in order for components to build properly on testing) the JS _does not build_ - as such, the stubs and copies were created with the relevant mapping being put in place within the Jest config. +This will change once unit testing of components (i.e. regression testing) is implemented and the config will be updated as required to use Jest environments. It was felt that at this point, rather than edit files that are integral to the running of the site, copies were the safer option. \ No newline at end of file diff --git a/src/frontend/test/component.js b/src/frontend/test/component.js new file mode 100644 index 000000000..38827e03b --- /dev/null +++ b/src/frontend/test/component.js @@ -0,0 +1,100 @@ +/** +* Attribute that's set on a component that's initialized +*/ +const componentInitializedAttr = 'data-component-initialized' + +/** + * Default component class. + * Components should inherit this class. + */ +class Component { + constructor(element) { + if (!(element instanceof HTMLElement)) { + throw new Error( + 'Components can only be initialized with an HTMLElement as argument to the constructor' + ) + } + + this.element = element + this.element.setAttribute(componentInitializedAttr, true) + } +} + +/** + * All registered component + */ +const registeredComponents = [] + +/** + * Register a component that can be initialized + * + * @export + * @param { Function } componentInitializer Function that will be called when component initializes + */ +const registerComponent = (componentInitializer) => { + registeredComponents.push(componentInitializer) +} + +/** + * Initialize all registered components in the defined scope + * + * @export + * @param {HTMLElement} scope The scope to initialize the components in. + */ +const initializeRegisteredComponents = (scope) => { + registeredComponents.forEach((componentInitializer) => { + componentInitializer(scope) + }) +} + +/** + * Get an Array of elements matching `selector` within `scope` + * + * @export + * @param {HTMLElement} scope The scope to select elements + * @param {String} selector The selector to select elements + * @returns {Array[HTMLElement]} An array of elements + */ +const getComponentElements = (scope, selector) => { + const elements = scope.querySelectorAll(selector) + if (!elements.length) { + return [] + } + + return Array.from(elements) +} + +/** + * Initialize component `Component` on all elements matching `selector` within `scope` + * Will only initialize elements that have not been initialized. + * + * @export + * @param {HTMLElement} scope The scope to initialize the objects on + * @param {String|Function} selector The selector to select elements + * @param {Component} ComponentClass The Component class to initialize + * @returns {Array[Component]} An array of initialized components + */ +const initializeComponent = (scope, selector, ComponentClass) => { + if (!(ComponentClass.prototype instanceof Component)) { + throw new Error( + 'Components can only be initialized when they inherit the basecomponent' + ) + } + + const elements = typeof (selector) === 'function' ? selector(scope) : getComponentElements(scope, selector) + if (!elements.length) { + return [] + } + + return elements + .filter((el) => !el.getAttribute(componentInitializedAttr)) + .map((el) => new ComponentClass(el)) +} + +export { + Component, + initializeComponent, + initializeRegisteredComponents, + getComponentElements, + registerComponent +} diff --git a/src/frontend/test/logging.js b/src/frontend/test/logging.js new file mode 100644 index 000000000..878c21f17 --- /dev/null +++ b/src/frontend/test/logging.js @@ -0,0 +1,34 @@ +// Fake logging class for testing +class Logging { + constructor() { + this.allowLogging = true + } + + log(message) { + if (this.allowLogging) { + console.log(message) + } + } + + info(message) { + if (this.allowLogging) { + console.info(message) + } + } + + warn(message) { + if (this.allowLogging) { + console.warn(message) + } + } + + error(message) { + if (this.allowLogging) { + console.error(message) + } + } +} + +const logging = new Logging + +export { logging } \ No newline at end of file diff --git a/src/frontend/test/validation.js b/src/frontend/test/validation.js new file mode 100644 index 000000000..7a48d3054 --- /dev/null +++ b/src/frontend/test/validation.js @@ -0,0 +1,300 @@ +// Bind events to a field to trigger validation +const initValidationOnField = (field) => { + // Input + if (field.hasClass('input--required')) { + const $fileButton = field.find('.input__file-label') + + // Document + if (field.hasClass('input--document')) { + const $fieldset = field.closest('.fieldset'); + const $checkboxGroup = field.find('.list'); + const $checkBoxes = $checkboxGroup.find('input[type="checkbox"]') + const $inputEl = field.find('.form-control-file') + + $fileButton.on('blur', (ev) => { validateCheckboxGroup($checkboxGroup) }) + $inputEl.on('change', (ev) => { validateCheckboxGroup($checkboxGroup) }) + $checkBoxes.on('blur change', (ev) => { validateCheckboxGroup($checkboxGroup) }) + + // Other input types + } else { + const $inputEl = field.find('input[required]') + const $fileButton = field.find('.input__file-label') + + $inputEl.on('blur change', (ev) => { setTimeout(() => { validateInput(field) }, 300)}) + $fileButton.on('blur', (ev) => { validateInput(field) } ) + } + + // Textarea + } else if (field.hasClass('textarea--required')) { + const $textareaEl = field.find('textarea[required]') + $textareaEl.on('blur change', (ev) => { setTimeout(() => { validateInput(field) }, 300)}) + + // Select + } else if (field.hasClass('select--required')) { + const $button = field.find('button') + const $inputEl = field.find('input[required]') + + $button.on('blur', (ev) => { setTimeout(() => { validateInput(field) }, 300)}) + $inputEl.on('change', (ev) => { validateInput(field) } ) + + // Radio-group + } else if (field.hasClass('radio-group--required')) { + const $radioButtons = field.find('input[required]') + $radioButtons.on('blur change', (ev) => { setTimeout(() => { validateRadioGroup(field) }, 300)} ) + + // Select-widget + } else if (field.hasClass('select-widget--required')) { + // Single select-widget + if (!field.hasClass('multi')) { + const $inputSearch = field.find('.form-control-search') + const $radioButtons = field.find('input[required]') + let inputBlurTimer + + $radioButtons.on('blur change', (ev) => { + inputBlurTimer = setTimeout(() => { + validateRadioGroup(field) + }, 300)} ) + + $inputSearch.on('blur', (ev) => { + inputBlurTimer = setTimeout(() => { + validateRadioGroup(field) + }, 300)} ) + + $radioButtons.on('focus', (ev) => { clearTimeout(inputBlurTimer) } ) + + // Multi select-widget + } else { + const $inputSearch = field.find('.form-control-search') + const $checkBoxes = field.find('input[type="checkbox"]') + let inputBlurTimer + + $checkBoxes.on('blur change', (ev) => { + inputBlurTimer = setTimeout(() => { + validateCheckboxGroup(field) + }, 300)} ) + + $inputSearch.on('blur', (ev) => { + inputBlurTimer = setTimeout(() => { + validateCheckboxGroup(field) + }, 300)} ) + + $checkBoxes.on('focus', (ev) => { clearTimeout(inputBlurTimer) } ) + + } + + // Tree + } else if (field.hasClass('tree--required')) { + const $inputSearch = field.find('.selected-tree-value') + const $jsTreeAnchors = field.find('.jstree-anchor') + let anchorBlurTimer + + $jsTreeAnchors.on('blur change', (ev) => { + anchorBlurTimer = setTimeout(() => { + validateTree(field) + }, 300)} ) + + $jsTreeAnchors.on('focus', (ev) => { clearTimeout(anchorBlurTimer) } ) + + } +} + +// Validate the required fields of a form +const validateRequiredFields = (form) => { + let isValidForm = true + + form.find(".input--required:not(.input--document), .textarea--required, .select--required").each((i, field) => { + if (!validateInput($(field))) { + expandCardValidate(field) + isValidForm = false + } + }) + + form.find(".input--document.input--required").each((i, field) => { + if (!validateCheckboxGroup($(field).closest('.fieldset').find('.list'))) { + expandCardValidate(field) + isValidForm = false + } + }) + + form.find(".radio-group--required").each((i, field) => { + if (!validateRadioGroup($(field))) { + expandCardValidate(field) + isValidForm = false + } + }) + + form.find(".select-widget--required").each((i, field) => { + if (!$(field).hasClass('multi')) { + if (!validateRadioGroup($(field))) { + expandCardValidate(field) + isValidForm = false + } + } else { + if (!validateCheckboxGroup($(field))) { + expandCardValidate(field) + isValidForm = false + } + } + + }) + + form.find(".tree--required").each((i, field) => { + if (!validateTree($(field))) { + $(field).closest('.card--expandable').find('.collapse').collapse('show') + isValidForm = false + } + }) + + return isValidForm +} + +const addErrorMessage = (field, name, id) => { + const $errorDiv = $('
') + let $span = $(``) + $span.text(`${name} is a required field.`) + $errorDiv.html($span) + field.append($errorDiv) +} + +const removeErrorMessage = (field) => { + field.find('.error').remove() +} + +const isHiddenDependentField = (field) => { + return (field.closest(".form-group[data-has-dependency='1'][style*='display: none']").length > 0) +} + +// Validate input field +const validateInput = (field) => { + const $inputEl = field.find('[required]') + const strFieldName = field.find('label').text() || '' + const strID = $inputEl.attr('id') || '' + + removeErrorMessage($(field)) + + if (($inputEl.val() === '') && (!isHiddenDependentField(field))) { + $inputEl.attr('aria-invalid', true) + addErrorMessage(field, strFieldName, strID) + field.addClass('invalid') + field.closest('.fieldset--required').addClass('fieldset--invalid') + return false + + } else { + $inputEl.removeAttr('aria-invalid') + removeErrorMessage(field) + field.removeClass('invalid') + field.closest('.fieldset--required').removeClass('fieldset--invalid') + return true + + } +} + +// Validate radio-group +const validateRadioGroup = (field) => { + const $radioButtons = field.find('input[required]') + const $fieldSet = field.closest('.fieldset--required') + const strFieldName = $fieldSet.find('.fieldset__legend legend').text() || '' + const strID = field.attr('id') || '' + let isChecked = false + + removeErrorMessage($(field)) + + $radioButtons.each((i, radioButton) => { + if ($(radioButton).is(":checked")) { + isChecked = true + } + }) + + if ((!isChecked) && (!isHiddenDependentField(field))) { + $radioButtons.attr('aria-invalid', true) + addErrorMessage(field, strFieldName, strID) + field.addClass('invalid') + field.closest('.fieldset--required').addClass('fieldset--invalid') + return false + + } else { + $radioButtons.removeAttr('aria-invalid') + removeErrorMessage(field) + field.removeClass('invalid') + field.closest('.fieldset--required').removeClass('fieldset--invalid') + return true + + } +} + +// Validate checkbox group +const validateCheckboxGroup = (field) => { + const $checkBoxes = field.find('input[type="checkbox"]') + const $fieldSet = field.closest('.fieldset--required') + const strFieldName = $fieldSet.find('.fieldset__legend legend').text() || '' + const strID = field.attr('id') || '' + let isChecked = false + + removeErrorMessage($(field)) + + $checkBoxes.each((i, checkBox) => { + if ($(checkBox).is(":checked")) { + isChecked = true + } + }) + + if ((!isChecked) && (!isHiddenDependentField(field))) { + addErrorMessage(field, strFieldName, strID) + field.addClass('invalid') + field.closest('.fieldset--required').addClass('fieldset--invalid') + return false + + } else { + removeErrorMessage(field) + field.removeClass('invalid') + field.closest('.fieldset--required').removeClass('fieldset--invalid') + return true + } + +} + +// Validate tree +const validateTree = (field) => { + const $inputEl = field.find('input[type="hidden"]') + const $fieldSet = field.closest('.fieldset--required') + const strFieldName = $fieldSet.find('.fieldset__legend legend').text() || '' + const strID = field.attr('id') || '' + + removeErrorMessage($(field)) + + if (((!$inputEl.length) || ($inputEl.val() === '')) && (!isHiddenDependentField(field))) { + $inputEl.attr('aria-invalid', true) + addErrorMessage(field, strFieldName, strID) + field.addClass('invalid') + field.closest('.fieldset--required').addClass('fieldset--invalid') + return false + + } else { + $inputEl.removeAttr('aria-invalid') + removeErrorMessage(field) + field.removeClass('invalid') + field.closest('.fieldset--required').removeClass('fieldset--invalid') + return true + + } +} + +// Expand the card with a certain field and scroll it into view +const expandCardValidate = (field) => { + const $collapse = $(field).closest('.card--expandable').find('.collapse') + // If the card is already expanded then just scroll straight to the field + if ($collapse.hasClass('show')) { + field.scrollIntoView() + } else { + // Otherwise add an event handler to scroll to the field, but only once the + // card has finished expanding (otherwise the scroll will happen before + // the card has finished expanding and it won't work) + $collapse.on('shown.bs.collapse.foobar', function(){ + field.scrollIntoView() + $(this).off('shown.bs.collapse.foobar'); + }) + $collapse.collapse('show') + } +} + +export { initValidationOnField, validateTree, validateRadioGroup, validateCheckboxGroup, validateRequiredFields }; diff --git a/tsconfig.json b/tsconfig.json index 1b8d649dd..d02f0c165 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,6 +8,11 @@ "allowJs": true, "moduleResolution": "node", "allowSyntheticDefaultImports": true, - "esModuleInterop": true - } + "esModuleInterop": true, + }, + "exclude": [ + "node_modules", + "dist", + "src/**/*.test.ts", + ] } diff --git a/webpack.config.js b/webpack.config.js index 011626e7b..2f643116c 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -42,12 +42,12 @@ module.exports = { rules: [ { test: /\.js$/, - exclude: /node_modules/, + exclude: [/node_modules/, /\.test\.js$/,/test/], use: ['babel-loader'] }, { test: /\.tsx?$/, - exclude: /node_modules/, + exclude: [/node_modules/, /\.test\.tsx?$/,/test/], use: ['babel-loader', 'ts-loader'] }, {