testing-library / cypress-testing-library

🐅 Simple and complete custom Cypress commands and utilities that encourage good testing practices.
http://npm.im/@testing-library/cypress
MIT License
1.8k stars 152 forks source link

Feature Request: Cypress mount is chainable but not with testing-library #187

Closed reintroducing closed 3 years ago

reintroducing commented 3 years ago

Relevant code or config

mount(
    <Button data-testid="test-id">
        Button
    </Button>
).findByTestId('test-id');

What you did: Cypress v7 introduced the mount method for component testing. Mount is chainable and you can run cypress commands against it, like the following, for example:

mount(<Button onClick={onClick}>Button onClick</Button>)
    .get('.Button-root')
    .click()
    .get('@onClick')
    .should('be.called');

What happened: I tried to apply this concept to a test using Cypress Testing Library with the aforementioned code and it failed in finding the testid. The following, however, works:

mount(
    <Button data-testid="test-id">
        Button
    </Button>
);

cy.findByTestId('test-id');

Reproduction repository:

Problem description: You cannot chain cypress testing library calls off of mount.

Suggested solution: Add support for chaining off of mount to align with the rest of the Cypress API.

NicholasBoll commented 3 years ago

mount is not part of the Cypress.Chainable interface and we cannot control what is returned by it. You could always create your own mount for your tests:

// support.ts/js

import { mount } from '@cypress/react'

declare global {
  namespace Cypress {
    interface Chainable {
      mount(node: React.ReactNode): Chainable<JQuery>
    }
  }
}

Cypress.Commands.add('mount', (node: React.ReactNode) => {
  mount(node)

  return cy.get('body');
})
reintroducing commented 3 years ago

@NicholasBoll thank you for your suggestion, and I did just try it out, but unfortunately just adding the import statement into the support file breaks the tests:

import {mount} from '@cypress/react';

results in

Screen Shot 2021-05-11 at 9 21 10 AM
reintroducing commented 3 years ago

err, disregard that, i'm trying this out in a different setup than is normal and just realized the root-most node_modules did not have react as a dep. my apologies.

reintroducing commented 3 years ago

@NicholasBoll Your approach does indeed work, but I'm left questioning if this is even necessary. At this point I'm fine with the additional cy. and not adding additional complexity into the setup. Thank you.

NicholasBoll commented 3 years ago

I agree. If Cypress Testing Library was a React-specific Cypress plugin, I think it would make sense to add a cy.mount. But Cypress and Cypress Testing Library do not require React. This is probably why Cypress didn't add a cy.mount command and instead require you to import mount and use it.