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

cypress-react-selector

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cypress-react-selector

cypress plugin to locate react elements by component, props and state

  • 0.1.6
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
21K
decreased by-6.24%
Maintainers
1
Weekly downloads
 
Created
Source

cypress-react-selector

Build Status

cypress-react-selector is a lightweight plugin to help you to locate web elements in your REACT app using components, props and states.. This extension allow you to select page elements in a way that is native to React. This will help you in functional UI tests and E2E tests.

Internally, cypress-react-selector uses a library called resq to query React's VirtualDOM in order to retrieve the nodes.

Table of Contents

Install and configure

Add as a dependency:

npm i --save cypress-react-selector

Include the commands

Update Cypress/support/index.js file to include the cypress-axe commands by adding:

import 'cypress-react-selector';

Alert

  • cypress-react-selector supports NodeJS 8 or higher
  • It supports React 16 or higher

Type Definition

interface Chainable {
  react(component: string, props?: {}, state?: {}): Chainable<Element>;
}

How to use React Selector?

Lets take this example REACT APP:

// imports

const MyComponent = ({ someBooleanProp }) => (
  <div>My Component {someBooleanProp ? 'show this' : ''} </div>
);

const App = () => (
  <div id="root">
    <MyComponent />
    <MyComponent someBooleanProp={true} />
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));

Wait for application to be ready to run tests

To wait until the React's component tree is loaded, add the waitForReact method to fixture's before hook.

before(() => {
  cy.visit('http://localhost:3000/myApp');
  cy.waitForReact();
});

this will wait to load react inside your app. By-default it will assume that the react root is set to '#root'. In the example above the id of the root element is set to 'root'. So, you don't need to pass the the root selector

The default timeout for waitForReact is 10000 ms. You can specify a custom timeout value:

cy.waitForReact(30000);

Wait to Load React for different react roots

It is always not true that the root of React app is set to 'root', may be your root element is 'mount', like:

const App = () => (
  <div id="mount">
    <MyComponent />
    <MyComponent name={'John'} />
  </div>
);

There is some application which displays react components asynchronously. The cypress-react-selector by-default assumes the react root element is set to 'root', if you have different root element, you need to pass that information to the react selector.

// if your react root is set to different selector other than 'root'
// then you don't need to pass root element information
cy.waitForReact(10000, '#mount');

Find Element by React Component

You should have React Develop Tool installed to spy and find out the component name as sometimes components can go though modifications. Once the React gets loaded, you can easily identify an web element by react component name:

cy.react('MyComponent');

// you can have your assertions chained like
it('it should validate react selection with component name', () => {
  cy.react('MyComponent').should('have.length', '1');
});

Element filtration by Props and States

You can filter the REACT components by its props and states like below:

cy.react(componentName, { propName: propValue }, { stateName: stateValue });

// for the example APP
cy.react('MyComponent', { name: 'John' });

Wildcard selection

You can select your components by partial name use a wildcard selectors:

// Partial Match
cy.react('My*', { name: 'John' });

// Entire Match
cy.react('*', { name: 'John' }); // return all components matched with the prop

Find element by nested props

Let's suppose you have an Form component

<Form>
  <Field name="email" type="email" component={MyTextInput} />
  <ErrorMessage name="email" component="div" />
  <br />
  <Field type="password" name="password" component={MyTextInput} />
  <ErrorMessage name="password" component="div" />
  <br />
  <button type="submit" disabled={isSubmitting}>
    Submit
  </button>
</Form>

And MyTextInput component is developed as:

const MyTextInput = (props) => {
  const { field, type } = props;

  return (
    <input {...field} type={type} placeholder={'ENTER YOUR ' + field.name} />
  );
};

then you can use cypress-react-selector to identify the element with nested props

it('enter data into the fields', () => {
  cy.react('MyTextInput', { field: { name: 'email' } }).type(
    'john.doe@cypress.com'
  );
  cy.react('MyTextInput', { field: { name: 'password' } }).type('whyMe?');
});

Get React Properties from element

Let's take same Form example

Get Props

You can get the React properties from a React element and validate the properties run time.

// set the email in the form
cy.react('MyTextInput', { field: { name: 'email' } }).type(
  'john.doe@cypress.com'
);

// validate the property runtime
cy.getReact('MyTextInput', { field: { name: 'email' } })
  .getProps('fields.value')
  .should('eq', 'john.doe@cypress.com');

// to get all the props, simply do not pass anything in getProps() method
cy.getReact('MyTextInput', { field: { name: 'email' } }).getProps();

get-props

Get current state

cy.getReact('MyTextInput', { field: { name: 'email' } }).getCurrentState(); // can return string | boolean | any[] | {}

Sample Tests

Checkout sample tests here

Use React Dev Tools plugin to easily identify the react component, props and state. Have a look in the below demonstration, how I have used the tool to write the sample test cases.

react-dev-tools

Sample Example Project

Credit goes to gregfenton for presenting a great example that uses Cypress-React-Selector. Checkout the work here

Tool You Need

React-Dev-Tool — You can inspect the DOM element by simply pressing the f12. But, to inspect REACT components and props, you need to install the chrome plugin.

Tell me your issues

you can raise any issue here

Contribution

Any pull request is welcome.

If this plugin helps you in your automation journey, choose to Sponsor

If it works for you , give a Star! :star:

- Copyright © 2020- Abhinaba Ghosh

Keywords

FAQs

Package last updated on 18 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