Skip to content

Commit

Permalink
fix: improve handling of userland injected styles in component testing (
Browse files Browse the repository at this point in the history
#16024)

* feat(npm/react): do not clear head between tests

* add a shared mount utils library

* add readme

* update dependencies

* add mount utils to circle

* change module

Co-authored-by: Barthélémy Ledoux <bart@cypress.io>
  • Loading branch information
lmiller1990 and Barthélémy Ledoux authored Apr 21, 2021
1 parent a6d504a commit fe0b63c
Show file tree
Hide file tree
Showing 16 changed files with 321 additions and 179 deletions.
13 changes: 13 additions & 0 deletions circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,15 @@ jobs:
path: npm/react/test_results
- store-npm-logs

npm-mount-utils:
<<: *defaults
steps:
- attach_workspace:
at: ~/
- run:
name: Build
command: yarn workspace @cypress/mount-utils build
- store-npm-logs

npm-create-cypress-tests:
<<: *defaults
Expand Down Expand Up @@ -1865,6 +1874,9 @@ linux-workflow: &linux-workflow
- npm-react:
requires:
- build
- npm-mount-utils:
requires:
- build
- npm-create-cypress-tests:
requires:
- build
Expand All @@ -1880,6 +1892,7 @@ linux-workflow: &linux-workflow
- npm-eslint-plugin-dev
- npm-create-cypress-tests
- npm-react
- npm-mount-utils
- npm-vue
- npm-design-system
- npm-webpack-batteries-included-preprocessor
Expand Down
Empty file added npm/mount-utils/CHANGELOG.md
Empty file.
10 changes: 10 additions & 0 deletions npm/mount-utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# @cypress/mount-utils

> **Note** this package is not meant to be used outside of cypress component testing.
This librares exports some shared types and utility functions designed to build adapters for components frameworks.

It is used in:

- [`@cypress/react`](https://github.com/cypress-io/cypress/tree/develop/npm/react)
- [`@cypress/vue`](https://github.com/cypress-io/cypress/tree/develop/npm/vue)
28 changes: 28 additions & 0 deletions npm/mount-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@cypress/mount-utils",
"version": "0.0.0-development",
"description": "Shared utilities for the various component testing adapters",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"build-prod": "tsc",
"watch": "tsc -w"
},
"dependencies": {},
"devDependencies": {
"typescript": "^4.2.3"
},
"files": [
"dist"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/cypress-io/cypress.git"
},
"homepage": "https://github.com/cypress-io/cypress/tree/master/npm/mount-utils#readme",
"bugs": "https://github.com/cypress-io/cypress/issues/new?template=1-bug-report.md",
"publishConfig": {
"access": "public"
}
}
82 changes: 81 additions & 1 deletion npm/react/src/utils.ts → npm/mount-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,66 @@
import { StyleOptions } from './mount'
/**
* Additional styles to inject into the document.
* A component might need 3rd party libraries from CDN,
* local CSS files and custom styles.
*/
export interface StyleOptions {
/**
* Creates <link href="..." /> element for each stylesheet
* @alias stylesheet
*/
stylesheets: string | string[]
/**
* Creates <link href="..." /> element for each stylesheet
* @alias stylesheets
*/
stylesheet: string | string[]
/**
* Creates <style>...</style> element and inserts given CSS.
* @alias styles
*/
style: string | string[]
/**
* Creates <style>...</style> element for each given CSS text.
* @alias style
*/
styles: string | string[]
/**
* Loads each file and creates a <style>...</style> element
* with the loaded CSS
* @alias cssFile
*/
cssFiles: string | string[]
/**
* Single CSS file to load into a <style></style> element
* @alias cssFile
*/
cssFile: string | string[]
}

export const ROOT_ID = '__cy_root'

/**
* Remove any style or extra link elements from the iframe placeholder
* left from any previous test
*
*/
export function cleanupStyles () {
const styles = document.body.querySelectorAll('[data-cy=injected-style-tag]')

styles.forEach((styleElement) => {
if (styleElement.parentElement) {
styleElement.parentElement.removeChild(styleElement)
}
})

const links = document.body.querySelectorAll('[data-cy=injected-stylesheet]')

links.forEach((link) => {
if (link.parentElement) {
link.parentElement.removeChild(link)
}
})
}

/**
* Insert links to external style resources.
Expand All @@ -14,6 +76,7 @@ function insertStylesheets (
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = href
link.dataset.cy = 'injected-stylesheet'
document.body.insertBefore(link, el)
})
}
Expand All @@ -25,6 +88,7 @@ function insertStyles (styles: string[], document: Document, el: HTMLElement | n
styles.forEach((style) => {
const styleElement = document.createElement('style')

styleElement.dataset.cy = 'injected-style-tag'
styleElement.appendChild(document.createTextNode(style))
document.body.insertBefore(styleElement, el)
})
Expand Down Expand Up @@ -124,3 +188,19 @@ export const injectStylesBeforeElement = (

return insertLocalCssFiles(cssFiles, document, el, options.log)
}

export function setupHooks (optionalCallback?: Function) {
// When running component specs, we cannot allow "cy.visit"
// because it will wipe out our preparation work, and does not make much sense
// thus we overwrite "cy.visit" to throw an error
Cypress.Commands.overwrite('visit', () => {
throw new Error(
'cy.visit from a component spec is not allowed',
)
})

beforeEach(() => {
optionalCallback?.()
cleanupStyles()
})
}
52 changes: 52 additions & 0 deletions npm/mount-utils/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */,
"module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"skipLibCheck": true,
"lib": [
"es2015",
"dom"
] /* Specify library files to be included in the compilation: */,
"allowJs": true /* Allow javascript files to be compiled. */,
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist" /* Redirect output structure to the directory. */,
// "rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": false /* Enable all strict type-checking options. */,
// "noImplicitAny": true,

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
"types": ["cypress"] /* Type declaration files to be included in compilation. */,
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules", "*.js"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import * as React from 'react'
import { mount } from '@cypress/react'
import styled, { ThemeProvider } from 'styled-components'

const lightest = '#FFFEFD'
const light = '#FEFCF1'
const darker = '#C49A03'
const darkest = '#382E0A'

export const theme = {
primaryDark: darkest,
primaryLight: lightest,
primaryLightDarker: light,
primaryHover: darker,
}

const styledComponentsStyle = 'margin-bottom:1rem'
const Line = styled.div`
${styledComponentsStyle}
`

export const SearchResults = (props) => {
return (
<div>
{props.results.map((result) => {
return (
<Line>
{result.title}
</Line>
)
})}
</div>
)
}

const mountComponent = ({ results }, options) => {
return mount(
<ThemeProvider theme={theme}>
<div style={{ margin: '6rem', maxWidth: '105rem' }}>
<SearchResults results={results} />
</div>
</ThemeProvider>,
options,
)
}

const inlineStyle = 'body { background: blue; }'
const bulmaCDN = 'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css'

describe('SearchResults', () => {
it('should inject styles into <head>', () => {
mountComponent({
results: [{ title: 'Org 1' }, { title: 'Org 2' }],
},
{
stylesheets: [bulmaCDN],
style: inlineStyle,
})

cy.get('link').should('exist')
cy.get('link').should('have.attr', 'href', bulmaCDN)
})

it('style-components injected styles from previous test should not be cleaned up \
but styles and stylesheets in mount should be', () => {
// style-components injected style should NOT have bene cleaned up
cy.get('style').should('contain.text', styledComponentsStyle)

// cleaned up inline <style> from previous test
cy.get('style').should('not.contain.text', inlineStyle)

// cleaned up bulma CDN link from previous test
cy.get('link').should('not.exist')

mountComponent({
results: [{ title: 'Org 1' }, { title: 'Org 2' }],
})
})
})
1 change: 1 addition & 0 deletions npm/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"watch": "yarn build --watch --watch.exclude ./dist/**/*"
},
"dependencies": {
"@cypress/mount-utils": "0.0.0-development",
"@cypress/webpack-preprocessor": "0.0.0-development",
"debug": "4.3.2",
"find-webpack": "2.2.1",
Expand Down
1 change: 1 addition & 0 deletions npm/react/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function createEntry (options) {
external: [
'react',
'react-dom',
'@cypress/mount-utils',
],
plugins: [
resolve(), commonjs(),
Expand Down
38 changes: 0 additions & 38 deletions npm/react/src/hooks.ts

This file was deleted.

Loading

0 comments on commit fe0b63c

Please sign in to comment.