Skycake
Skycake

Reputation: 11

Cannot get react components with Cypress + cypress-react-selector

I'm trying to setup React testing with Cypress + cypress-react-selector. Cypress seems to be working fine, but cypress-react-selector not so much. I can run normal cypress methods. But when I run cy.react(), it throws: "Could not find instance of React in given element" I've been googling a lot, but nothing helps.

MyComponent.js

`
import React from 'react';

export const MyComponent = () => {
  return <div data-testid="myTestId">my text</div>;
};

`

MyComponent.cy.js

`

import React from 'react';
import { MyComponent } from './MyComponent';

describe('<MyComponent />', () => {
  beforeEach(() => {
    cy.mount(<MyComponent />);
  });

  it('renders', () => {
    //this works
    cy.get('[data-testid=myTestId]').should('have.text', 'my text');

    //this seems to be working, but I don't know
    cy.waitForReact(5000, '#__cy_root');

    //This fails with: "Could not find instance of React in given element"
    cy.react('MyComponent');
  });
});

`

cypress/support/component.js

`

import 'cypress-react-selector';

import './commands';

import { mount } from 'cypress/react18';

Cypress.Commands.add('mount', mount);`

cypress/support/component-index.html

`

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Components App</title>
  </head>
  <body>
    <div id="__cy_root" data-cy-root></div>
  </body>
</html>

`

cypress.config.js ` const { defineConfig } = require('cypress');

module.exports = defineConfig({
  env: {
    'cypress-react-selector': {
      root: '#__cy_root',
    },
  },
  component: {
    devServer: {
      framework: 'create-react-app',
      bundler: 'webpack',
    },
  },
});

`

Ask for code, if I haven't provided something.

Upvotes: 1

Views: 1387

Answers (1)

T.Beard
T.Beard

Reputation: 158

cypress-react-selector pre-dates cypress component testing, and I don't see any sign that it has been updated to handle component testing - all examples are e2e style testing.

Logically, Cypress built-in component testing and cypress-react-selector do the same thing, so maybe consider using one or the other.

IMO the cypress-react-selector has somewhat better API and more accessible examples, for instance I can't see how to do this in Cypress component testing

cypress-react-selector#sample-tests

Get current state

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

Upvotes: 2

Related Questions