0.0.3 • Published 5 years ago

@rckeller/cypress-react v0.0.3

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

@rckeller/cypress-react

Unofficial Cypress utilities for testing React applications. Typescript definitions are included.

npm i -D @rckeller/cypress-react

Configuring Unit Testing

You can register cy.mount by importing it, which will initialize loading and caching for React, ReactDOM and component styles between test runs.

// support/index.js
import '@rckeller/cypress-react/mount'

cy.mount performs a full mount of a given component on a page, and aliases it as @ComponentName unless otherwise specified. You are free to access its properties, state, and even invoke its own methods. Unlike Jest and Enzyme, which simulate a thin virtual DOM that lacks full support for event propagination and other functionality, these components will be mounted on a live page in isolation that more closely represents a real use case.

// in a test file
cy.mount(<HelloWorld />)

cy.get('@HelloWorld')
  .invoke('setState', { name: 'React' })
cy.get('@HelloWorld')
  .its('state')
  .should('deep.equal', { name: 'React' })

Optionally, you can register a superset of cy.get, which aliases components by their displayname and allows you to select them in several different ways like so:

// support/index.js
import '@rckeller/cypress-unfetch/mount/get'
//  now you have access to new component selectors

// in a test file
cy.mount(<HelloWorld />)

cy.get('@HelloWorld')
cy.get(<HelloWorld />)
cy.get(HelloWorld)

Note, components are mounted in a fresh DOM, without any styles loaded. If you want to load components with styles, define Cypress.Styles as a link tag with your styles inlines.

// inline styles
Cypress.Styles = `<style type="text/css">p { color: black; }</style>`
// or use a CDN
Cypress.Styles = `<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">`

Using a CDN may violate the same-origin policy, in which case, you'd have to set chromeWebSecurity to false in cypress.json.

Further Reading

This module is based on the official cypress-react-unit-test recipe, and is merely an abstraction layer for that implemetation. The original repository contains many different examples of how to take advantage of Cypress for unit testing components.