DEV Community

loading...

Discussion on: React Testing Crash Course

Collapse
bahmutov profile image
Gleb Bahmutov

Hi Gábor, excellent blog post as usual.

I took liberty forking your TodoMVC repo into github.com/bahmutov/todomvc-react and adding a Cypress component test. Rather than using synthetic JSDom, Cypress can mount a React component using github.com/bahmutov/cypress-react-... and run it. Then it becomes a "normal" realistic test. For example, the Footer component - let's mount it with a few props and click on the "clear completed" button to make sure it calls the passed function.

import React from 'react';
import { mount } from 'cypress-react-unit-test';
import { Footer } from './footer';
// import app's style so the footer looks real
import 'todomvc-app-css/index.css';

describe('footer component', () => {
  it('calls onClearCompleted if there are completed items', () => {
    mount(
      <section className="todoapp">
        <Footer itemsLeft={10} completedCount={2} 
             onClearCompleted={cy.stub().as('clear')} />
      </section>
    );
    // component is running like a mini web app
    // we can interact with it using normal Cypress commands
    // https://on.cypress.io/api
    cy.contains('Clear completed').click();
    cy.get('@clear').should('have.been.calledOnce');
  });
});

When you run the test you see the footer, just like you would in a real application. You can debug each command, for example seeing where the click happened.

For more details, see github.com/bahmutov/cypress-react-... and happy testing!

Collapse
vuesomedev profile image
Gábor Soós Author

This component testing with Cypress deserves a separate post :)

Forem Open with the Forem app