Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cypress-react-unit-test

Package Overview
Dependencies
Maintainers
1
Versions
109
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cypress-react-unit-test

Unit test React components using Cypress

  • 4.1.2
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

cypress-react-unit-test CircleCI Cypress.io tests renovate-app badge This project is using Percy.io for visual regression testing.

A little helper to unit test React components in the open source Cypress.io E2E test runner v4.5.0+

TLDR

  • What is this? This package allows you to use Cypress test runner to unit test your React components with zero effort. Here is a typical component testing, notice there is not external URL shown, since it is mounting the component directly.

Example component test

  • How is this different from Enzyme or RTL? It is similar in functionality BUT runs the component in the real browser with full power of Cypress E2E test runner: live GUI, full API, screen recording, CI support, cross-platform, and visual testing. Ohh, and the code coverage is built-in!
  • If you like using @testing-library/react, you can use @testing-library/cypress for the same findBy, queryBy commands, see one of the examples in the list below
  • Read My Vision for Component Tests in Cypress

Comparison

FeatureJest / Enzyme / RTLCypress + cypress-react-unit-test
Test runs in real browser
Uses full mount
Test speed🏎as fast as the app works in the browser
Test can use additional pluginsmaybeuse any Cypress plugin
Test can interact with componentsynthetic limited APIuse any Cypress command
Test can be debuggedvia terminal and Node debuggeruse browser DevTools
Built-in time traveling debuggerCypress time traveling debugger
Re-run tests on file or test change
Test output on CIterminalterminal, screenshots, videos
Tests can be run in parallel✅ via parallelization
Test against interfaceif using @testing-library/react✅ and can use @testing-library/cypress
Spying and mockingJest mocksSinon library
Code coverage

Known problems

See issues labeled v4

Install

Requires Node version 8 or above.

npm install --save-dev cypress cypress-react-unit-test
  1. Include this plugin from your project's cypress/support/index.js
require('cypress-react-unit-test/support')
  1. Tell Cypress how your React application is transpiled or bundled (using Webpack), so Cypress can load your components. For example, if you use react-scripts do:
// cypress/plugins/index.js
module.exports = (on, config) => {
  require('cypress-react-unit-test/plugins/react-scripts')(on, config)
  // IMPORTANT to return the config object
  // with the any changed environment variables
  return config
}

See Recipes for more examples.

  1. ⚠️ Turn the experimental component support on in your cypress.json. You can also specify where component spec files are located. For example, to have them located in src folder use:
{
  "experimentalComponentTesting": true,
  "componentFolder": "src"
}

Examples

import React from 'react'
import { mount } from 'cypress-react-unit-test'
import { HelloWorld } from './hello-world.jsx'
describe('HelloWorld component', () => {
  it('works', () => {
    mount(<HelloWorld />)
    // now use standard Cypress commands
    cy.contains('Hello World!').should('be.visible')
  })
})

Look at the examples in cypress/component folder. Here is the list in progress

Basic examples

SpecDescription
alert-spec.jsComponent tries to use window.alert
counter-set-stateCounter component that uses this.state
counter-use-hooksCounter component that uses useState hook
emotion-spec.jsConfirms the component is using @emotion/core and styles are set
error-boundary-spec.jsChecks if an error boundary component works
pure-component-spec.jsTests stateless component
stateless-spec.jsPasses Cypress stub to the component, confirms the component calls it on click
window-spec.jsIn the component test, the spec window and the application's window where the component is running should be the same object
cssShows that component with import './Button.css' works
networkConfirms we can use cy.route to stub / spy on component's network calls
react-book-by-chris-noringCopied test examples from React Book and adapted for Cypress component tests
react-tutorialTests from official ReactJS tutorial copied and adapted for Cypress component tests
stub-exampleUses cy.stub as component props
stylesAdd extra styles to the component during testing using style, cssFile or stylesheets mount options
toggle-exampleTesting a toggle component using Cypress DOM commands
typescriptA spec written in TypeScript
unmountVerifies the component's behavior when it is unmounted from the DOM
use-lodash-fpImports and tests methods from lodash/fp dependency
document-specChecks document dimensions from the component
styled-componentsTest components that use styled-components

plus a few smaller sanity specs in cypress/component/basic folder.

Advanced examples

SpecDescription
app-action-exampleApp actions against components
contextConfirms components that use React context feature work
forward-refTests a component that uses a forward ref feature
hooksTests several components that use React Hooks like useState, useCallback
lazy-loadedConfirms components that use React.lazy and dynamic imports work
material-ui-exampleLarge components demos from Material UI
mock-fetchTest stubs window.fetch used by component in useEffect hook
mocking-componentReplaced a child component with dummy component during test
mocking-importsStub a named ES6 import using plugin-transform-modules-commonjs with loose: true when transpiled
react-router-v6Example testing a React Router v6
renderlessTesting a component that does not need to render itself into the DOM
set-timeout-exampleControl the clock with cy.tick and test loading components that use setTimeout
testing-lib-exampleA spec adopted from @testing-library/react that uses @testing-library/cypress
timersTesting components that set timers, adopted from ReactJS Testing recipes
tutorialA few tests adopted from ReactJS Tutorial
portalComponent test for ReactDOM.createPortal feature
react-bootstrapConfirms react-bootstrap components are working

Large examples

This way of component testing has been verified in a number of forked 3rd party projects.

RepoDescription
try-cra-with-unit-testHello world initialized with CRAv3
try-cra-app-typescriptHello world initialized with CRAv3 --typescript
react-todo-with-hooksModern web application using hooks
test-redux-examplesExample apps copies from official Redux repo and tested as components
test-react-hooks-animationsTesting React springs fun blob animation
test-mdx-exampleExample testing MDX components using Cypress
test-apolloComponent testing an application that uses Apollo GraphQL library
test-xstate-reactXState component testing using Cypress
test-react-router-v5A few tests of React Router v5
test-material-uiTesting Material UI components: date pickers, lists, autocomplete
test-d3-react-gaugeTesting React D3 gauges
storybook-code-coverageExample app where we get 100% code coverage easily with a single integration spec and a few component specs, replacing several tools
react-loading-skeletonOne to one Storybook tests for React skeleton components. Uses local .babelrc settings without Webpack config
test-swrComponent test for Zeit SWR hooks for remote data fetching
emoji-searchQuick component test for a fork of emoji-search
test-custom-error-boundaryPlay with a component that implements error boundary
Jscrambler-Webpack-ReactExample project with its own Webpack config file

To find more examples, see GitHub topic cypress-react-unit-test-example

Options

You can pass additional styles, css files and external stylesheets to load, see docs/styles.md for full list.

const todo = {
  id: '123',
  title: 'Write more tests',
}
mount(<Todo todo={todo} />, {
  stylesheets: [
    'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css',
  ],
})
Additional configuration If your React and React DOM libraries are installed in non-standard paths (think monorepo scenario), you can tell this plugin where to find them. In `cypress.json` specify paths like this:
{
  "env": {
    "cypress-react-unit-test": {
      "react": "node_modules/react/umd/react.development.js",
      "react-dom": "node_modules/react-dom/umd/react-dom.development.js"
    }
  }
}

Code coverage

If you are using plugins/cra-v3 it instruments the code on the fly using babel-plugin-istanbul and generates report using dependency cypress-io/code-coverage (included). If you want to disable code coverage instrumentation and reporting, use --env coverage=false or CYPRESS_coverage=false or set in your cypress.json file

{
  "env": {
    "coverage": false
  }
}

Visual testing

You can use any Visual Testing plugin from these component tests. This repo uses Percy.io visual diffing service as a GitHub pull request check.

Development

See docs/development.md

Migration guide

From v3 to v4

The old v3 master branch is available as branch v3

  • the cy.mount is now simply import { mount } from 'cypress-react-unit-test'
  • the support file is simply require('cypress-react-unit-test/support')

Same feature for unit testing components from other frameworks using Cypress

Keywords

FAQs

Package last updated on 02 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc