diff --git a/.env b/.env new file mode 100644 index 0000000..ef282fa --- /dev/null +++ b/.env @@ -0,0 +1,3 @@ +# Jest configuration variables +# - possible values: ON, OFF +JEST_USE_SETUP=OFF \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..0cbd65c --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,65 @@ +const fs = require('fs'); +const path = require('path'); +const projectRootPath = fs.realpathSync(__dirname + '/../../../'); + +let voltoPath = path.join(projectRootPath, 'node_modules/@plone/volto'); +let configFile; +if (fs.existsSync(`${projectRootPath}/tsconfig.json`)) + configFile = `${projectRootPath}/tsconfig.json`; +else if (fs.existsSync(`${projectRootPath}/jsconfig.json`)) + configFile = `${projectRootPath}/jsconfig.json`; + +if (configFile) { + const jsConfig = require(configFile).compilerOptions; + const pathsConfig = jsConfig.paths; + if (pathsConfig['@plone/volto']) + voltoPath = `./${jsConfig.baseUrl}/${pathsConfig['@plone/volto'][0]}`; +} + +const AddonConfigurationRegistry = require(`${voltoPath}/addon-registry.js`); +const reg = new AddonConfigurationRegistry(projectRootPath); + +// Extends ESlint configuration for adding the aliases to `src` directories in Volto addons +const addonAliases = Object.keys(reg.packages).map((o) => [ + o, + reg.packages[o].modulePath, +]); + +const addonExtenders = reg.getEslintExtenders().map((m) => require(m)); + +const defaultConfig = { + extends: `${voltoPath}/.eslintrc`, + settings: { + 'import/resolver': { + alias: { + map: [ + ['@plone/volto', '@plone/volto/src'], + ['@plone/volto-slate', '@plone/volto/packages/volto-slate/src'], + ...addonAliases, + ['@package', `${__dirname}/src`], + ['@root', `${__dirname}/src`], + ['~', `${__dirname}/src`], + ], + extensions: ['.js', '.jsx', '.json'], + }, + 'babel-plugin-root-import': { + rootPathSuffix: 'src', + }, + }, + }, + rules: { + 'react/jsx-no-target-blank': [ + 'error', + { + allowReferrer: true, + }, + ], + } +}; + +const config = addonExtenders.reduce( + (acc, extender) => extender.modify(acc), + defaultConfig, +); + +module.exports = config; diff --git a/.gitignore b/.gitignore index 53b9801..f1be4ff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ .vscode/ .history -.eslintrc.js .nyc_output project coverage diff --git a/.project.eslintrc.js b/.project.eslintrc.js deleted file mode 100644 index 765070f..0000000 --- a/.project.eslintrc.js +++ /dev/null @@ -1,48 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -const projectRootPath = fs.existsSync('./project') - ? fs.realpathSync('./project') - : fs.realpathSync('./../../../'); -const packageJson = require(path.join(projectRootPath, 'package.json')); -const jsConfig = require(path.join(projectRootPath, 'jsconfig.json')).compilerOptions; - -const pathsConfig = jsConfig.paths; - -let voltoPath = path.join(projectRootPath, 'node_modules/@plone/volto'); - -Object.keys(pathsConfig).forEach(pkg => { - if (pkg === '@plone/volto') { - voltoPath = `./${jsConfig.baseUrl}/${pathsConfig[pkg][0]}`; - } -}); -const AddonConfigurationRegistry = require(`${voltoPath}/addon-registry.js`); -const reg = new AddonConfigurationRegistry(projectRootPath); - -// Extends ESlint configuration for adding the aliases to `src` directories in Volto addons -const addonAliases = Object.keys(reg.packages).map(o => [ - o, - reg.packages[o].modulePath, -]); - - -module.exports = { - extends: `${projectRootPath}/node_modules/@plone/volto/.eslintrc`, - settings: { - 'import/resolver': { - alias: { - map: [ - ['@plone/volto', '@plone/volto/src'], - ...addonAliases, - ['@package', `${__dirname}/src`], - ['~', `${__dirname}/src`], - ], - extensions: ['.js', '.jsx', '.json'], - }, - 'babel-plugin-root-import': { - rootPathSuffix: 'src', - }, - }, - }, -}; - diff --git a/Jenkinsfile b/Jenkinsfile index ddc8646..ff59546 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -13,7 +13,8 @@ pipeline { DEPENDENCIES = "" BACKEND_PROFILES = "eea.kitkat:testing" BACKEND_ADDONS = "" - VOLTO = "16" + VOLTO = "17" + VOLTO16_BREAKING_CHANGES = "no" IMAGE_NAME = BUILD_TAG.toLowerCase() } @@ -44,6 +45,7 @@ pipeline { } steps { script { + checkout scm withCredentials([string(credentialsId: 'eea-jenkins-token', variable: 'GITHUB_TOKEN')]) { check_result = sh script: '''docker run --pull always -i --rm --name="$IMAGE_NAME-gitflow-check" -e GIT_TOKEN="$GITHUB_TOKEN" -e GIT_BRANCH="$BRANCH_NAME" -e GIT_ORG="$GIT_ORG" -e GIT_NAME="$GIT_NAME" eeacms/gitflow /check_if_testing_needed.sh''', returnStatus: true @@ -61,7 +63,6 @@ pipeline { allOf { not { environment name: 'CHANGE_ID', value: '' } environment name: 'CHANGE_TARGET', value: 'develop' - environment name: 'SKIP_TESTS', value: '' } allOf { environment name: 'CHANGE_ID', value: '' @@ -69,25 +70,27 @@ pipeline { not { changelog '.*^Automated release [0-9\\.]+$' } branch 'master' } - environment name: 'SKIP_TESTS', value: '' } } } - stages { - stage('Build test image') { - steps { - checkout scm - sh '''docker build --pull --build-arg="VOLTO_VERSION=$VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend''' + parallel { + + stage('Volto 17') { + agent { node { label 'docker-1.13'} } + stages { + stage('Build test image') { + steps { + sh '''docker build --pull --build-arg="VOLTO_VERSION=$VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend''' + } } - } - - stage('Fix code') { - when { + + stage('Fix code') { + when { environment name: 'CHANGE_ID', value: '' not { branch 'master' } - } - steps { - script { + } + steps { + script { fix_result = sh(script: '''docker run --name="$IMAGE_NAME-fix" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend ci-fix''', returnStatus: true) sh '''docker cp $IMAGE_NAME-fix:/app/src/addons/$GIT_NAME/src .''' sh '''docker rm -v $IMAGE_NAME-fix''' @@ -105,31 +108,31 @@ pipeline { sh '''exit 1''' } } + } } - } - stage('ES lint') { - steps { - sh '''docker run --rm --name="$IMAGE_NAME-eslint" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend lint''' + stage('ES lint') { + when { environment name: 'SKIP_TESTS', value: '' } + steps { + sh '''docker run --rm --name="$IMAGE_NAME-eslint" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend lint''' + } } - } - stage('Style lint') { - steps { - sh '''docker run --rm --name="$IMAGE_NAME-stylelint" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend stylelint''' + stage('Style lint') { + when { environment name: 'SKIP_TESTS', value: '' } + steps { + sh '''docker run --rm --name="$IMAGE_NAME-stylelint" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend stylelint''' + } } - } - stage('Prettier') { - steps { - sh '''docker run --rm --name="$IMAGE_NAME-prettier" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend prettier''' + stage('Prettier') { + when { environment name: 'SKIP_TESTS', value: '' } + steps { + sh '''docker run --rm --name="$IMAGE_NAME-prettier" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend prettier''' + } } - } - - stage('Coverage Tests') { - parallel { - - stage('Unit tests') { + stage('Unit tests') { + when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { @@ -155,17 +158,24 @@ pipeline { } } } - } + } - stage('Integration tests') { + stage('Integration tests') { + when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' - sh '''docker run -d --shm-size=3g --link $IMAGE_NAME-plone:plone --name="$IMAGE_NAME-cypress" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend start-ci''' + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone:plone --name="$IMAGE_NAME-cypress" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend start-ci''' + frontend = sh script:'''docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress make check-ci''', returnStatus: true + if ( frontend != 0 ) { + sh '''docker logs $IMAGE_NAME-cypress; exit 1''' + } + sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress make cypress-ci''' } finally { try { + if ( frontend == 0 ) { sh '''rm -rf cypress-videos cypress-results cypress-coverage cypress-screenshots''' sh '''mkdir -p cypress-videos cypress-results cypress-coverage cypress-screenshots''' videos = sh script: '''docker cp $IMAGE_NAME-cypress:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos/''', returnStatus: true @@ -189,6 +199,7 @@ pipeline { sh '''for file in $(find cypress-results -name *.xml); do if [ $(grep -E 'failures="[1-9].*"' $file | wc -l) -eq 0 ]; then testname=$(grep -E 'file=.*failures="0"' $file | sed 's#.* file=".*\\/\\(.*\\.[jsxt]\\+\\)" time.*#\\1#' ); rm -f cypress-videos/videos/$testname.mp4; fi; done''' archiveArtifacts artifacts: 'cypress-videos/**/*.mp4', fingerprint: true, allowEmptyArchive: true } + } } finally { catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { junit testResults: 'cypress-results/**/*.xml', allowEmptyResults: true @@ -204,16 +215,7 @@ pipeline { } } } - } } - } - } - post { - always { - sh script: "docker rmi $IMAGE_NAME-frontend", returnStatus: true - } - } - } stage('Report to SonarQube') { when { @@ -221,9 +223,11 @@ pipeline { allOf { not { environment name: 'CHANGE_ID', value: '' } environment name: 'CHANGE_TARGET', value: 'develop' + environment name: 'SKIP_TESTS', value: '' } allOf { environment name: 'CHANGE_ID', value: '' + environment name: 'SKIP_TESTS', value: '' anyOf { allOf { branch 'develop' @@ -248,14 +252,107 @@ pipeline { } } + + } + } + + stage('Volto 16') { + agent { node { label 'integration'} } + when { + environment name: 'SKIP_TESTS', value: '' + not { environment name: 'VOLTO16_BREAKING_CHANGES', value: 'yes' } + } + stages { + stage('Build test image') { + steps { + sh '''docker build --pull --build-arg="VOLTO_VERSION=16" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend16''' + } + } + + stage('Unit tests Volto 16') { + steps { + script { + try { + sh '''docker run --name="$IMAGE_NAME-volto16" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend16 test-ci''' + sh '''rm -rf xunit-reports16''' + sh '''mkdir -p xunit-reports16''' + sh '''docker cp $IMAGE_NAME-volto16:/app/junit.xml xunit-reports16/''' + } finally { + catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { + junit testResults: 'xunit-reports16/junit.xml', allowEmptyResults: true + } + sh script: '''docker rm -v $IMAGE_NAME-volto16''', returnStatus: true + } + } + } + } + + stage('Integration tests Volto 16') { + steps { + script { + try { + sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone16" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone16:plone --name="$IMAGE_NAME-cypress16" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend16 start-ci''' + frontend = sh script:'''docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress16 make check-ci''', returnStatus: true + if ( frontend != 0 ) { + sh '''docker logs $IMAGE_NAME-cypress16; exit 1''' + } + sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress16 make cypress-ci''' + } finally { + try { + if ( frontend == 0 ) { + sh '''rm -rf cypress-videos16 cypress-results16 cypress-coverage16 cypress-screenshots16''' + sh '''mkdir -p cypress-videos16 cypress-results16 cypress-coverage16 cypress-screenshots16''' + videos = sh script: '''docker cp $IMAGE_NAME-cypress16:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos16/''', returnStatus: true + sh '''docker cp $IMAGE_NAME-cypress16:/app/src/addons/$GIT_NAME/cypress/reports cypress-results16/''' + screenshots = sh script: '''docker cp $IMAGE_NAME-cypress16:/app/src/addons/$GIT_NAME/cypress/screenshots cypress-screenshots16''', returnStatus: true + + archiveArtifacts artifacts: 'cypress-screenshots16/**', fingerprint: true, allowEmptyArchive: true + + if ( videos == 0 ) { + sh '''for file in $(find cypress-results16 -name *.xml); do if [ $(grep -E 'failures="[1-9].*"' $file | wc -l) -eq 0 ]; then testname=$(grep -E 'file=.*failures="0"' $file | sed 's#.* file=".*\\/\\(.*\\.[jsxt]\\+\\)" time.*#\\1#' ); rm -f cypress-videos16/videos/$testname.mp4; fi; done''' + archiveArtifacts artifacts: 'cypress-videos16/**/*.mp4', fingerprint: true, allowEmptyArchive: true + } + } + } finally { + catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { + junit testResults: 'cypress-results16/**/*.xml', allowEmptyResults: true + } + catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { + sh '''docker logs $IMAGE_NAME-cypress16''' + } + sh script: "docker stop $IMAGE_NAME-cypress16", returnStatus: true + sh script: "docker stop $IMAGE_NAME-plone16", returnStatus: true + sh script: "docker rm -v $IMAGE_NAME-plone16", returnStatus: true + sh script: "docker rm -v $IMAGE_NAME-cypress16", returnStatus: true + } + } + } + } + } + + } + } + } + post { + always { + sh script: "docker rmi $IMAGE_NAME-frontend", returnStatus: true + sh script: "docker rmi $IMAGE_NAME-frontend16", returnStatus: true + } + } + } + + stage('SonarQube compare to master') { when { anyOf { allOf { not { environment name: 'CHANGE_ID', value: '' } environment name: 'CHANGE_TARGET', value: 'develop' + environment name: 'SKIP_TESTS', value: '' } allOf { + environment name: 'SKIP_TESTS', value: '' environment name: 'CHANGE_ID', value: '' branch 'develop' not { changelog '.*^Automated release [0-9\\.]+$' } @@ -316,3 +413,4 @@ pipeline { } } } + diff --git a/Makefile b/Makefile index efbf2fb..522b577 100644 --- a/Makefile +++ b/Makefile @@ -46,7 +46,7 @@ endif DIR=$(shell basename $$(pwd)) NODE_MODULES?="../../../node_modules" PLONE_VERSION?=6 -VOLTO_VERSION?=16 +VOLTO_VERSION?=17 ADDON_PATH="${DIR}" ADDON_NAME="@eeacms/${ADDON_PATH}" DOCKER_COMPOSE=PLONE_VERSION=${PLONE_VERSION} VOLTO_VERSION=${VOLTO_VERSION} ADDON_NAME=${ADDON_NAME} ADDON_PATH=${ADDON_PATH} docker compose @@ -86,7 +86,7 @@ cypress-open: ## Open cypress integration tests .PHONY: cypress-run cypress-run: ## Run cypress integration tests - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development $(NODE_MODULES)/cypress/bin/cypress run --browser chromium + CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development $(NODE_MODULES)/cypress/bin/cypress run .PHONY: test test: ## Run jest tests @@ -98,7 +98,7 @@ test-update: ## Update jest tests snapshots .PHONY: stylelint stylelint: ## Stylelint - $(NODE_MODULES)/stylelint/bin/stylelint.js --allow-empty-input 'src/**/*.{css,less}' + $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' .PHONY: stylelint-overrides stylelint-overrides: @@ -106,7 +106,7 @@ stylelint-overrides: .PHONY: stylelint-fix stylelint-fix: ## Fix stylelint - $(NODE_MODULES)/stylelint/bin/stylelint.js --allow-empty-input 'src/**/*.{css,less}' --fix + $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' --fix $(NODE_MODULES)/.bin/stylelint --custom-syntax less --allow-empty-input 'theme/**/*.overrides' 'src/**/*.overrides' --fix .PHONY: prettier @@ -119,11 +119,11 @@ prettier-fix: ## Fix prettier .PHONY: lint lint: ## ES Lint - $(NODE_MODULES)/eslint/bin/eslint.js --max-warnings=0 'src/**/*.{js,jsx}' + $(NODE_MODULES)/.bin/eslint --max-warnings=0 'src/**/*.{js,jsx}' .PHONY: lint-fix lint-fix: ## Fix ES Lint - $(NODE_MODULES)/eslint/bin/eslint.js --fix 'src/**/*.{js,jsx}' + $(NODE_MODULES)/.bin/eslint --fix 'src/**/*.{js,jsx}' .PHONY: i18n i18n: ## i18n @@ -155,8 +155,11 @@ start-ci: cd ../.. yarn start +.PHONY: check-ci +check-ci: + $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 + .PHONY: cypress-ci cypress-ci: $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 - NODE_ENV=development make cypress-run - + CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development $(NODE_MODULES)/cypress/bin/cypress run --browser chromium diff --git a/cypress/support/e2e.js b/cypress/support/e2e.js index f696418..f8f752c 100644 --- a/cypress/support/e2e.js +++ b/cypress/support/e2e.js @@ -35,10 +35,6 @@ export const slateBeforeEach = (contentType = 'Document') => { path: 'cypress', }); cy.visit('/cypress/my-page'); - cy.waitForResourceToLoad('@navigation'); - cy.waitForResourceToLoad('@breadcrumbs'); - cy.waitForResourceToLoad('@actions'); - cy.waitForResourceToLoad('@types'); cy.waitForResourceToLoad('my-page'); cy.navigate('/cypress/my-page/edit'); }; diff --git a/jest-addon.config.js b/jest-addon.config.js index 3c86610..39d6433 100644 --- a/jest-addon.config.js +++ b/jest-addon.config.js @@ -1,3 +1,5 @@ +require('dotenv').config({ path: __dirname + '/.env' }) + module.exports = { testMatch: ['**/src/addons/**/?(*.)+(spec|test).[jt]s?(x)'], collectCoverageFrom: [ @@ -9,18 +11,26 @@ module.exports = { '@plone/volto/cypress': '/node_modules/@plone/volto/cypress', '@plone/volto/babel': '/node_modules/@plone/volto/babel', '@plone/volto/(.*)$': '/node_modules/@plone/volto/src/$1', - '@package/(.*)$': '/src/$1', - '@root/(.*)$': '/src/$1', + '@package/(.*)$': '/node_modules/@plone/volto/src/$1', + '@root/(.*)$': '/node_modules/@plone/volto/src/$1', '@plone/volto-quanta/(.*)$': '/src/addons/volto-quanta/src/$1', + '@eeacms/search/(.*)$': '/src/addons/volto-searchlib/searchlib/$1', + '@eeacms/search': '/src/addons/volto-searchlib/searchlib', '@eeacms/(.*?)/(.*)$': '/node_modules/@eeacms/$1/src/$2', - '@plone/volto-slate': + '@plone/volto-slate$': '/node_modules/@plone/volto/packages/volto-slate/src', + '@plone/volto-slate/(.*)$': + '/node_modules/@plone/volto/packages/volto-slate/src/$1', '~/(.*)$': '/src/$1', 'load-volto-addons': '/node_modules/@plone/volto/jest-addons-loader.js', }, + transformIgnorePatterns: [ + '/node_modules/(?!(@plone|@root|@package|@eeacms)/).*/', + ], transform: { '^.+\\.js(x)?$': 'babel-jest', + '^.+\\.ts(x)?$': 'babel-jest', '^.+\\.(png)$': 'jest-file', '^.+\\.(jpg)$': 'jest-file', '^.+\\.(svg)$': './node_modules/@plone/volto/jest-svgsystem-transform.js', @@ -33,4 +43,9 @@ module.exports = { statements: 5, }, }, -}; + ...(process.env.JEST_USE_SETUP === 'ON' && { + setupFilesAfterEnv: [ + '/node_modules/@eeacms/volto-object-widget/jest.setup.js', + ], + }), +} diff --git a/jest.setup.js b/jest.setup.js new file mode 100644 index 0000000..85b16f7 --- /dev/null +++ b/jest.setup.js @@ -0,0 +1,65 @@ +import { jest } from '@jest/globals'; +import configureStore from 'redux-mock-store'; +import thunk from 'redux-thunk'; +import { blocksConfig } from '@plone/volto/config/Blocks'; +import installSlate from '@plone/volto-slate/index'; + +var mockSemanticComponents = jest.requireActual('semantic-ui-react'); +var mockComponents = jest.requireActual('@plone/volto/components'); +var config = jest.requireActual('@plone/volto/registry').default; + +config.blocks.blocksConfig = { + ...blocksConfig, + ...config.blocks.blocksConfig, +}; + +jest.doMock('semantic-ui-react', () => ({ + __esModule: true, + ...mockSemanticComponents, + Popup: ({ content, trigger }) => { + return ( +
+
{trigger}
+
{content}
+
+ ); + }, +})); + +jest.doMock('@plone/volto/components', () => { + return { + __esModule: true, + ...mockComponents, + SidebarPortal: ({ children }) => , + }; +}); + +jest.doMock('@plone/volto/registry', () => + [installSlate].reduce((acc, apply) => apply(acc), config), +); + +const mockStore = configureStore([thunk]); + +global.fetch = jest.fn(() => + Promise.resolve({ + json: () => Promise.resolve({}), + }), +); + +global.store = mockStore({ + intl: { + locale: 'en', + messages: {}, + formatMessage: jest.fn(), + }, + content: { + create: {}, + subrequests: [], + }, + connected_data_parameters: {}, + screen: { + page: { + width: 768, + }, + }, +}); diff --git a/package.json b/package.json index e3a4cd8..97036f3 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "@cypress/code-coverage": "^3.10.0", "@plone/scripts": "*", "babel-plugin-transform-class-properties": "^6.24.1", + "dotenv": "^16.3.2", "husky": "^8.0.3", "lint-staged": "^14.0.1", "md5": "^2.3.0" diff --git a/src/Widget/ObjectListWidget.test.jsx b/src/Widget/ObjectListWidget.test.jsx index 8684dcc..3facd47 100644 --- a/src/Widget/ObjectListWidget.test.jsx +++ b/src/Widget/ObjectListWidget.test.jsx @@ -1,8 +1,7 @@ import React from 'react'; -import renderer from 'react-test-renderer'; import configureStore from 'redux-mock-store'; import { Provider } from 'react-intl-redux'; -import { render, fireEvent } from '@testing-library/react'; +import { render, screen, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import ObjectListWidget, { FlatObjectList, @@ -58,7 +57,7 @@ test('renders an object list widget component', () => { }, }); - const component = renderer.create( + const { container } = render( { , ); - const json = component.toJSON(); - expect(json).toMatchSnapshot(); + expect(screen.getByLabelText('My Widget')).toBeInTheDocument(); + + const inputField = container.querySelector('[name="my-widget"]'); + expect(inputField).toBeInTheDocument(); + expect(inputField).toHaveValue('2 x Link'); + expect(inputField).toBeDisabled(); + + expect( + container.querySelector('button[aria-label="Edit"]'), + ).toBeInTheDocument(); + expect( + container.querySelector('button[aria-label="Delete"]'), + ).toBeInTheDocument(); + + const bigPenButton = screen.getByTestId('big-pen-button'); + expect(bigPenButton).toBeInTheDocument(); + expect(bigPenButton).toHaveClass('ui button item ui noborder button'); + expect(bigPenButton).toHaveAttribute('title', 'Edit'); + expect(bigPenButton.querySelector('svg')).toHaveStyle({ + fill: 'blue', + height: '18px', + width: 'auto', + }); + + // Assert the help text + expect(screen.getByText('My description')).toBeInTheDocument(); + expect(screen.getByText('My description')).toHaveClass('help'); }); test('renders an object list widget component and changes its value by clicking a button', async () => { @@ -128,11 +152,76 @@ test('renders an object list widget component and changes its value by clicking ); - const { getByText, asFragment, rerender, getByTestId, getAllByText } = render( - jsx, + const { container, getByText, rerender, getByTestId, getAllByText } = + render(jsx); + + // Assert the outer container + const outerContainer = container.querySelector( + '.inline.required.field.help.text.field-wrapper-my-widget', + ); + expect(outerContainer).toBeInTheDocument(); + + // Assert the label + const label = screen.getByLabelText('My Widget'); + expect(label).toBeInTheDocument(); + expect(label).toHaveAttribute('id', 'field-my-widget'); + + // Assert the toolbar + const toolbar = container.querySelector('.toolbar'); + expect(toolbar).toBeInTheDocument(); + expect(toolbar).toHaveStyle({ 'z-index': '2' }); + + const editButton = toolbar.querySelector('button[aria-label="Edit"]'); + expect(editButton).toBeInTheDocument(); + expect(editButton).toHaveClass('item ui noborder button'); + expect(editButton.querySelector('i')).toHaveClass( + 'blue write square large icon', + ); + + const deleteButton = toolbar.querySelector('button[aria-label="Delete"]'); + expect(deleteButton).toBeInTheDocument(); + expect(deleteButton).toHaveClass('item ui noborder button'); + expect(deleteButton.querySelector('i')).toHaveClass('red close large icon'); + + // Assert the input field + const inputField = container.querySelector('#field-my-widget'); + expect(inputField).toBeInTheDocument(); + expect(inputField).toHaveAttribute('name', 'my-widget'); + expect(inputField).toHaveAttribute('type', 'text'); + expect(inputField).toHaveValue('2 x Link'); + expect(inputField).toBeDisabled(); + + const bigPenButton = screen.getByTestId('big-pen-button'); + expect(bigPenButton).toBeInTheDocument(); + expect(bigPenButton).toHaveClass('ui button item ui noborder button'); + expect(bigPenButton).toHaveAttribute('title', 'Edit'); + expect(bigPenButton.querySelector('svg')).toHaveStyle({ + fill: 'blue', + height: '18px', + width: 'auto', + }); + + const deleteButton2 = container.querySelector('button[aria-label="Delete"]'); + expect(deleteButton2).toBeInTheDocument(); + expect(deleteButton2).toHaveClass('ui button item ui noborder button'); + + const deleteButtonSvg = container.querySelector( + 'button[aria-label="Delete"] svg', ); + expect(deleteButtonSvg).toHaveStyle({ + fill: 'red', + height: '18px', + width: 'auto', + }); - expect(asFragment()).toMatchSnapshot(); + // Assert the help text + const helpText = screen.getByText('My description'); + expect(helpText).toBeInTheDocument(); + expect(helpText).toHaveClass('help'); + + // Assert the additional button + const extraButton = screen.getByText('Click me !'); + expect(extraButton).toBeInTheDocument(); // click the button which changes data outside of modal fireEvent.click(getByText('Click me !')); @@ -142,8 +231,6 @@ test('renders an object list widget component and changes its value by clicking // click on the first External tab fireEvent.click(getAllByText('External')[0]); - - expect(asFragment()).toMatchSnapshot(); }); test('renders a flat object list component with an item', async () => { @@ -166,22 +253,123 @@ test('renders a flat object list component with an item', async () => { ); - const { asFragment, getAllByText } = render(jsx); + const { getAllByText, container } = render(jsx); + + const outerContainer = container.querySelector('.objectlist-widget-content'); + expect(outerContainer).toBeInTheDocument(); + + // Assert the first grid layout + const firstGrid = outerContainer.querySelector('.ui.grid:first-child'); + expect(firstGrid).toBeInTheDocument(); + + const firstGridColumn = firstGrid.querySelector('.eleven.wide.column'); + expect(firstGridColumn).toBeInTheDocument(); + + const firstSegment = firstGridColumn.querySelector('.ui.segment'); + expect(firstSegment).toBeInTheDocument(); + + const firstObjectListItems = firstSegment.querySelectorAll( + '.mocked-default-widget', + ); + expect(firstObjectListItems).toHaveLength(1); + expect(firstObjectListItems[0]).toHaveAttribute( + 'id', + 'mocked-field-internal_link-0-my-widget-0', + ); + expect(firstObjectListItems[0]).toHaveTextContent( + 'Internal link - No description', + ); + + // Assert the second grid layout + const secondGrid = outerContainer.querySelector('.ui.grid:nth-child(2)'); + expect(secondGrid).toBeInTheDocument(); + + const secondGridColumn = secondGrid.querySelector('.eleven.wide.column'); + expect(secondGridColumn).toBeInTheDocument(); + + const secondSegment = secondGridColumn.querySelector('.ui.segment'); + expect(secondSegment).toBeInTheDocument(); + + const secondObjectListItems = secondSegment.querySelectorAll( + '.mocked-default-widget', + ); + expect(secondObjectListItems).toHaveLength(1); + expect(secondObjectListItems[0]).toHaveAttribute( + 'id', + 'mocked-field-internal_link-0-my-widget-1', + ); + expect(secondObjectListItems[0]).toHaveTextContent( + 'Internal link - No description', + ); + + // Assert the delete buttons + const deleteButtons = container.querySelectorAll( + 'button[aria-label="Delete"]', + ); + expect(deleteButtons).toHaveLength(2); + deleteButtons.forEach((button) => { + expect(button).toBeInTheDocument(); + expect(button).toHaveClass('ui mini basic circular button'); + expect(button).toHaveAttribute('title', 'Delete'); + const deleteButtonSvg = button.querySelector('svg'); + expect(deleteButtonSvg).toBeInTheDocument(); + expect(deleteButtonSvg).toHaveStyle({ + height: '18px', + width: 'auto', + fill: 'currentColor', + }); + }); + + const segment = firstGridColumn.querySelector('.ui.segment'); + expect(segment).toBeInTheDocument(); - // verify the first tab - expect(asFragment()).toMatchSnapshot(); + const tabMenu = segment.querySelector('.ui.attached.tabular.menu'); + expect(tabMenu).toBeInTheDocument(); + const tabMenuItems = tabMenu.querySelectorAll('.item'); + expect(tabMenuItems).toHaveLength(3); + expect(tabMenuItems[0]).toHaveClass('active'); + expect(tabMenuItems[0]).toHaveTextContent('Internal'); + expect(tabMenuItems[1]).toHaveTextContent('External'); + expect(tabMenuItems[2]).toHaveTextContent('Email'); + const activeTab = segment.querySelector( + '.ui.bottom.attached.segment.active.tab', + ); + expect(activeTab).toBeInTheDocument(); + const activeTabContent = activeTab.querySelector('.mocked-default-widget'); + expect(activeTabContent).toBeInTheDocument(); + expect(activeTabContent).toHaveAttribute( + 'id', + 'mocked-field-internal_link-0-my-widget-0', + ); + expect(activeTabContent).toHaveTextContent('Internal link - No description'); // load second tab in first item fireEvent.click(getAllByText('External')[0]); - // verify the second tab in the first item - expect(asFragment()).toMatchSnapshot(); + const activeTabContentAfterClick = activeTab.querySelector( + '.mocked-default-widget', + ); + expect(activeTabContentAfterClick).toBeInTheDocument(); + expect(activeTabContentAfterClick).toHaveAttribute( + 'id', + 'mocked-field-external_link-0-my-widget-0', + ); + + expect(activeTabContentAfterClick).toHaveTextContent( + 'External URL (can be relative within this site or absolute if it starts with http:// or https://) - No description', + ); // load second tab in second item fireEvent.click(getAllByText('External')[1]); - // verify the second tab in the second item - expect(asFragment()).toMatchSnapshot(); + const activeTabContentAfterClick1 = container.querySelector( + '#mocked-field-external_link-0-my-widget-1', + ); + expect(activeTabContentAfterClick1).toBeInTheDocument(); + + expect(activeTabContentAfterClick1).toHaveTextContent( + 'External URL (can be relative within this site or absolute if it starts with http:// or https://) - No description', + ); }); test('renders a modal object list form component and tests it in various ways', () => { @@ -220,7 +408,7 @@ test('renders a modal object list form component and tests it in various ways', ); - const { asFragment, getByText, rerender, getByTestId } = render(jsx); + const { getByText, rerender, getByTestId } = render(jsx); // set value prop to something else than the value before from outside the modal valueState = [{ external_link: 'https://duckduckgo.com' }]; @@ -228,7 +416,6 @@ test('renders a modal object list form component and tests it in various ways', // in the modal there should be just a single item with the link: https://duckduckgo.com // (actual result: empty snapshot because of https://github.com/Semantic-Org/Semantic-UI-React/issues/3959) - expect(asFragment()).toMatchSnapshot(); window.HTMLElement.prototype.scrollIntoView = jest.fn(); @@ -289,7 +476,7 @@ test('renders a modal object list form component and tests it in other various w ); - const { asFragment, getByTitle, getByText, rerender } = render(jsx); + const { getByTitle, getByText, rerender } = render(jsx); fireEvent.click(getByTitle('Cancel')); @@ -306,5 +493,4 @@ test('renders a modal object list form component and tests it in other various w expect(valueState.length).toEqual(3); // actual result: empty snapshot because of https://github.com/Semantic-Org/Semantic-UI-React/issues/3959 - expect(asFragment()).toMatchSnapshot(); }); diff --git a/src/Widget/__snapshots__/ObjectListWidget.test.jsx.snap b/src/Widget/__snapshots__/ObjectListWidget.test.jsx.snap deleted file mode 100644 index 53b1364..0000000 --- a/src/Widget/__snapshots__/ObjectListWidget.test.jsx.snap +++ /dev/null @@ -1,771 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`renders a flat object list component with an item 1`] = ` - -
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-`; - -exports[`renders a flat object list component with an item 2`] = ` - -
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-`; - -exports[`renders a flat object list component with an item 3`] = ` - -
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-
-
- -
- -
-
-
-
-
-
- -
-
-
-
-
-`; - -exports[`renders a modal object list form component and tests it in other various ways 1`] = ``; - -exports[`renders a modal object list form component and tests it in various ways 1`] = ``; - -exports[`renders an object list widget component 1`] = ` -
-
-
-
-
- -
-
-
-
-