Giter Site home page Giter Site logo

testing-library / cypress-testing-library Goto Github PK

View Code? Open in Web Editor NEW
1.8K 1.8K 150.0 674 KB

πŸ… Simple and complete custom Cypress commands and utilities that encourage good testing practices.

Home Page: http://npm.im/@testing-library/cypress

License: MIT License

JavaScript 69.00% HTML 23.44% TypeScript 7.56%
testing

cypress-testing-library's Introduction

@testing-library/angular

Octopus with the Angular logo

Simple and complete Angular testing utilities that encourage good testing practices.


Read The Docs | Edit the docs



Build Status version downloads MIT License

All Contributors PRs Welcome Code of Conduct Discord

Watch on GitHub Star on GitHub Tweet

Open in GitHub Codespaces

Table of Contents

The problem

You want to write maintainable tests for your Angular components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

This solution

The @testing-library/angular is a very lightweight solution for testing Angular components. It provides light utility functions on top of Angular and @testing-library/dom, in a way that encourages better testing practices. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

Example

counter.component.ts

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="decrement()">-</button>
    <span>Current Count: {{ counter }}</span>
    <button (click)="increment()">+</button>
  `,
})
export class CounterComponent {
  @Input() counter = 0;

  increment() {
    this.counter += 1;
  }

  decrement() {
    this.counter -= 1;
  }
}

counter.component.spec.ts

import { render, screen, fireEvent } from '@testing-library/angular';
import { CounterComponent } from './counter.component';

describe('Counter', () => {
  test('should render counter', async () => {
    await render(CounterComponent, { componentProperties: { counter: 5 } });

    expect(screen.getByText('Current Count: 5'));
  });

  test('should increment the counter on click', async () => {
    await render(CounterComponent, { componentProperties: { counter: 5 } });

    const incrementButton = screen.getByRole('button', { name: '+' });
    fireEvent.click(incrementButton);

    expect(screen.getByText('Current Count: 6'));
  });
});

See more examples

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install @testing-library/angular --save-dev

You may also be interested in installing jest-dom so you can use the custom jest matchers.

Docs

Version compatibility

Angular Angular Testing Library
17.x 15.x, 14.x, 13.x
16.x 14.x, 13.x
>= 15.1 14.x, 13.x
< 15.1 12.x, 11.x
14.x 12.x, 11.x

Guiding Principles

The more your tests resemble the way your software is used, the more confidence they can give you.

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your Angular components are used.

Utilities are included in this project based on the following guiding principles:

  1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
  2. It should be generally useful for testing individual Angular components or full Angular applications.
  3. Utility implementations and APIs should be simple and flexible.

At the end of the day, what we want is for this library to be pretty light-weight, simple, and understandable.

Contributors

Thanks goes to these people (emoji key):

Tim Deschryver
Tim Deschryver

πŸ’» πŸ“– πŸš‡ ⚠️
MichaΓ«l De Boey
MichaΓ«l De Boey

πŸ“–
Ignacio Le Fluk
Ignacio Le Fluk

πŸ’» ⚠️
TamΓ‘s SzabΓ³
TamΓ‘s SzabΓ³

πŸ’»
Gregor Woiwode
Gregor Woiwode

πŸ’»
Toni Villena
Toni Villena

πŸ› πŸ’» πŸ“– ⚠️
ShPelles
ShPelles

πŸ“–
Miluoshi
Miluoshi

πŸ’» ⚠️
Nick McCurdy
Nick McCurdy

πŸ“–
Srinivasan Sekar
Srinivasan Sekar

πŸ“–
Bitcollage
Bitcollage

πŸ“–
Emil Sundin
Emil Sundin

πŸ’»
Ombrax
Ombrax

πŸ’»
Rafael Santana
Rafael Santana

πŸ’» ⚠️ πŸ›
Benjamin Blackwood
Benjamin Blackwood

πŸ“– ⚠️
Gustavo Porto
Gustavo Porto

πŸ“–
Bo Vandersteene
Bo Vandersteene

πŸ’»
Janek
Janek

πŸ’» ⚠️
Gleb Irovich
Gleb Irovich

πŸ’» ⚠️
Arjen
Arjen

πŸ’» 🚧
Suguru Inatomi
Suguru Inatomi

πŸ’» πŸ€”
Amit Miran
Amit Miran

πŸš‡
Jan-Willem Willebrands
Jan-Willem Willebrands

πŸ’»
Sandro
Sandro

πŸ’» πŸ›
Michael Westphal
Michael Westphal

πŸ’» ⚠️
Lukas
Lukas

πŸ’»
Matan Borenkraout
Matan Borenkraout

🚧
mleimer
mleimer

πŸ“– ⚠️
MeIr
MeIr

πŸ› ⚠️
John Dengis
John Dengis

πŸ’» ⚠️
Rokas BrazdΕΎionis
Rokas BrazdΕΎionis

πŸ’»
Mateus Duraes
Mateus Duraes

πŸ’»
Josh Joseph
Josh Joseph

πŸ’» ⚠️
Torsten Knauf
Torsten Knauf

🚧
antischematic
antischematic

πŸ› πŸ€”
Florian Pabst
Florian Pabst

πŸ’»
Mark Goho
Mark Goho

🚧 πŸ“–
Jan-Willem Baart
Jan-Willem Baart

πŸ’» ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Docs

Read The Docs | Edit the docs

FAQ

I am using Reactive Forms and the jest-dom matcher toHaveFormValues always returns an empty object or there are missing fields. Why?

Only form elements with a name attribute will have their values passed to toHaveFormsValues.

Issues

Looking to contribute? Look for the Good First Issue label.

πŸ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

πŸ’‘ Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a πŸ‘. This helps maintainers prioritize what to work on.

See Feature Requests

❓ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

Getting started with GitHub Codespaces

To get started, create a codespace for this repository by clicking this πŸ‘‡

Open in GitHub Codespaces

A codespace will open in a web-based version of Visual Studio Code. The dev container is fully configured with software needed for this project.

Note: Dev containers is an open spec which is supported by GitHub Codespaces and other tools.

LICENSE

MIT

cypress-testing-library's People

Contributors

aaronmcadam avatar abeplays avatar adrians5j avatar afontcu avatar airato avatar alexkrolick avatar allcontributors[bot] avatar amitmiran137 avatar bastibuck avatar bluewinds avatar dasblitz avatar existentialism avatar flopieutd avatar frederickfogerty avatar gnapse avatar juliusdelta avatar kentcdodds avatar leschdom avatar marktnoonan avatar michaeldeboey avatar nicholasboll avatar nickmccurdy avatar nielsdb97 avatar noriste avatar npeterkamps avatar ppi-buck avatar simenb avatar sompylasar avatar thegallery avatar weyert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cypress-testing-library's Issues

CypressError: cy.findByText() failed because it requires the subject be a global 'document' object.

  • cypress-testing-library version: 5.2.0
  • node version: 13.7.0
  • npm (or yarn) version: 6.13.6

Relevant code or config

it('should validate the credentials', () => {
    cy.findByText(/Log me in/i)
      .click()
      .findByText(/Username should not be empty/i)
      .findByText(/Password should not be empty/i);
});

What you did: Bump @testing-library/cypress from 5.0.2 to 5.2.0

What happened:

  1) Register page should validate the data:                                                                                                                                                                                      [149/2152]
     CypressError: cy.findByText() failed because it requires the subject be a global 'document' object.                                                                                                                                    

The subject received was:

<span.MuiButton-label>

The previous command that ran was:

cy.click()

All 3 subject validations failed on this subject.
at Object.cypressErr (http://localhost:3000/__cypress/runner/cypress_runner.js:86207:11)
at Object.throwErr (http://localhost:3000/__cypress/runner/cypress_runner.js:86162:18)
at Object.throwErrByPath (http://localhost:3000/__cypress/runner/cypress_runner.js:86194:17)
at ensureDocument (http://localhost:3000/__cypress/runner/cypress_runner.js:74338:21)
at validateType (http://localhost:3000/__cypress/runner/cypress_runner.js:74184:16)
at Object.ensureSubjectByType (http://localhost:3000/__cypress/runner/cypress_runner.js:74210:9)
at pushSubjectAndValidate (http://localhost:3000/__cypress/runner/cypress_runner.js:81127:15)
at Context. (http://localhost:3000/__cypress/runner/cypress_runner.js:81413:18)
at http://localhost:3000/__cypress/runner/cypress_runner.js:80892:33
at tryCatcher (http://localhost:3000/__cypress/runner/cypress_runner.js:120203:23)
at Promise._settlePromiseFromHandler (http://localhost:3000/__cypress/runner/cypress_runner.js:118139:31)
at Promise._settlePromise (http://localhost:3000/__cypress/runner/cypress_runner.js:118196:18)
at Promise._settlePromiseCtx (http://localhost:3000/__cypress/runner/cypress_runner.js:118233:10)
at Async../node_modules/bluebird/js/release/async.js.Async._drainQueue (http://localhost:3000/__cypress/runner/cypress_runner.js:114933:12)
at Async../node_modules/bluebird/js/release/async.js.Async._drainQueues (http://localhost:3000/__cypress/runner/cypress_runner.js:114938:10)
at Async.drainQueues (http://localhost:3000/__cypress/runner/cypress_runner.js:114812:14)

https://github.com/leosuncin/mui-next-ts/pull/26/checks?check_run_id=421662750

Reproduction repository:

https://github.com/leosuncin/mui-next-ts/tree/dependabot/npm_and_yarn/testing-library/cypress-5.2.0

Problem description:

Suggested solution:

it('should validate the credentials', () => {
    cy.findByText(/Log me in/i)
      .click();
    cy.findByText(/Username should not be empty/i)
      .findByText(/Password should not be empty/i);
});

All(?) timeouts report as "cy.then() timed out after waiting '4000ms'" rather than printing actual expectation failure

  • cypress-testing-library version: 5.0.1
  • node version: 12.6.0
  • npm (or yarn) version: 1.17.3

Since upgrading to 5.0.1, it seems any timeouts are all being reported as Your callback function returned a promise which never resolved.

Any expectation that times out now just prints out the below, which obviously makes it pretty difficult to know which assertion it's actually failing on.

     CypressError: cy.then() timed out after waiting '4000ms'.

Your callback function returned a promise which never resolved.

The callback function was:

thenArgs => {
        const getValue = () => {
          const value = commandImpl(thenArgs.document);
          const result = Cypress.$(value); // Overriding the selector of the jquery object because it's displayed in the long message of .should('exist') failure message
          // Hopefully it makes it clearer, because I find the normal response of "Expected to find element '', but never found it" confusing

          result.selector = `${queryName}(${queryArgument(args)})`;

          if (result.length > 0) {
            consoleProps.yielded = result.toArray();
          }

          return result;
        };

        const resolveValue = () => {
          // retry calling "getValue" until following assertions pass or this command times out
          return Cypress.Promise.try(getValue).then(value => {
            return cy.verifyUpcomingAssertions(value, waitOptions, {
              onRetry: resolveValue
            });
          });
        };

        if (queryRegex.test(queryName)) {
          // For get* queries, do not retry
          return getValue();
        }

        return resolveValue().then(subject => {
          // Remove the error that occurred because it is irrelevant now
          if (consoleProps.error) {
            delete consoleProps.error;
          }

          return subject;
        });
      }

getBy* with .should('not.exist')

The behavior of cypress-testing-library's getBy queries is a bit different than the cypress built-in .get() method: the built-in will retry should('not.exist') until it times out, but the getBy queries timeout on the query. One workaround is to change to getBy to queryBy, but this requires a little bit of extra dom-testing-library knowledge that can confuse people coming from Cypress, and still doesn't retry.

Alternative

// This doesn't work
cy.getByTestId('my-item').should('not.exist');

// This works for verifying an element isn't present *right now*
cy.queryByTestId('my-item').should('be.null');

// This should retry but does not
cy.queryByTestId('my-item').should('not.exist');

Idea

It might make sense for queryBy* to actually be aliased to getBy* in the cypress context?

EDIT: actually the .should() chain should really trigger a retry of the parent command. Maybe custom commands don't hook into .should correctly?

Related to #23, cypress-io/cypress#3109

Timed out retrying: cy.click() failed because this element is detached from the DOM

  • cypress-testing-library version: ^6.0.1
  • node version: v12.13.1
  • npm (or yarn) version: npm v6.12.1

Relevant code or config

cy.findByText('Submit CTA')
      .should('exist')
      .click()

What happened:

 CypressError: Timed out retrying: cy.click() failed because this element is detached from the DOM.

Problem description:
This problem is outlined in this thread cypress-io/cypress#7306 where DOM nodes are detached prior to attempting the clicks. I thought that #78 would take care of that problem but it looks like the problem exists when running the code above. As you can imagine this makes tests flaky and it doesn't look like cypress has native support for this yet.

In this post they provide a workaround to this problem by using the pipe plugin however when used in combination with cypress-testing-library it looks like the problem still exists.

I'm posting here simply because we are using the library and I was wondering if #78 was intended to fix this issue and I'm not sure if maybe I'm misusing findByText. Any help or direction is appreciated.
Thanks

TypeError: container.querySelectorAll is not a function

  • cypress-testing-library version: 5.1.1
  • node version: 12.4.0
  • npm (or yarn) version: 1.21.1 (yarn)

Relevant code or config

describe('anonymous calculator', () => {
  it('can make calculations', () => {
    cy.visit('/')
      .findByText(/^1$/)
      .click()
      .findByText(/^\+$/)
      .click()
      .findByText(/^2$/)
      .click()
      .findByText(/^=$/)
      .click()
      .findByTestId('total')
      .should('have.text', '3')
  })
})

What you did: Attempted to run tjs/cypress-04 branch of https://github.com/kentcdodds/jest-cypress-react-babel-webpack/tree/tjs/cypress-04

What happened:

Screen Shot 2020-01-30 at 1 52 55 PM

Reproduction repository:
https://github.com/kentcdodds/jest-cypress-react-babel-webpack/tree/tjs/cypress-04

Problem description:

TypeError: container.querySelectorAll is not a function

Suggested solution:

--

@types/testing-library__cypress is breaking my CI build

Apparently it tries to download two versions of Cypress simultaneously. One that I defined ("cypress": "3.8.1") and one at @types/testing-library__cypress ("cypress": "^3.5.0").

Relevant issue at cypress side: cypress-io/cypress#4595.

  • cypress-testing-library version: "@testing-library/cypress": "5.0.2"
  • node version: 10.18
  • npm (or yarn) version: 6.13

CI LOG:

error /app/node_modules/@types/testing-library__cypress/node_modules/cypress: Command failed.
Exit code: 1
Command: node index.js --exec install
Arguments: 
Directory: /app/node_modules/@types/testing-library__cypress/node_modules/cypress
Output:
Installing Cypress (version: 3.6.1)

[16:39:59]  Downloading Cypress     [started]
[16:40:00]  Downloading Cypress      0% 0s [title changed]
[16:40:00]  Downloading Cypress      3% 3s [title changed]
[16:40:00]  Downloading Cypress      4% 5s [title changed]
[16:40:00]  Downloading Cypress      4% 8s [title changed]
[16:40:00]  Downloading Cypress      5% 8s [title changed]
[16:40:00]  Downloading Cypress      6% 8s [title changed]
[16:40:00]  Downloading Cypress      7% 9s [title changed]
[16:40:01]  Downloading Cypress      8% 9s [title changed]
[16:40:01]  Downloading Cypress      9% 9s [title changed]
[16:40:01]  Downloading Cypress      10% 9s [title changed]
[16:40:01]  Downloading Cypress      12% 8s [title changed]
[16:40:01]  Downloading Cypress      13% 8s [title changed]
[16:40:01]  Downloading Cypress      13% 9s [title changed]
[16:40:01]  Downloading Cypress      14% 9s [title changed]
[16:40:01]  Downloading Cypress      15% 9s [title changed]
[16:40:01]  Downloading Cypress      15% 10s [title changed]
[16:40:02]  Downloading Cypress      16% 9s [title changed]
[16:40:02]  Downloading Cypress      18% 9s [title changed]
[16:40:02]  Downloading Cypress      19% 9s [title changed]
[16:40:02]  Downloading Cypress      21% 8s [title changed]
[16:40:02]  Downloading Cypress      22% 8s [title changed]
[16:40:02]  Downloading Cypress      24% 7s [title changed]
[16:40:02]  Downloading Cypress      25% 7s [title changed]
[16:40:02]  Downloading Cypress      26% 7s [title changed]
[16:40:02]  Downloading Cypress      27% 7s [title changed]
[16:40:02]  Downloading Cypress      29% 7s [title changed]
[16:40:03]  Downloading Cypress      31% 6s [title changed]
[16:40:03]  Downloading Cypress      34% 6s [title changed]
[16:40:03]  Downloading Cypress      35% 6s [title changed]
[16:40:03]  Downloading Cypress      36% 6s [title changed]
[16:40:03]  Downloading Cypress      39% 5s [title changed]
[16:40:03]  Downloading Cypress      40% 5s [title changed]
[16:40:03]  Downloading Cypress      45% 4s [title changed]
[16:40:03]  Downloading Cypress      47% 4s [title changed]
[16:40:03]  Downloading Cypress      60% 2s [title changed]
[16:40:04]  Downloading Cypress      73% 1s [title changed]
[16:40:04]  Downloading Cypress      85% 1s [title changed]
[16:40:04]  Downloading Cypress      100% 0s [title changed]
[16:40:06]  Downloading Cypress      100% 0s [failed]
[16:40:06] β†’ The Cypress App could not be downloaded.

Does your workplace require a proxy to be used to access the Internet? If so, you must configure the HTTP_PROXY environment variable before downloading Cypress. Read more: https://on.cypress.io/proxy-configuration

Otherwise, please check network connectivity and try again:

----------

URL: https://download.cypress.io/desktop/3.6.1?platform=linux&arch=x64
Error: Corrupted download

Expected downloaded file to have checksum: 1c887ae436316e59f53be57d0c0a8c1e4b483ad40dd7b7e90d2da740f777eb64f93838d09446a2c48cd68f0292d710f1f53a03afff4e0f2d47d410767c90387a
Computed checksum: 47134d7281c1188d04d0cdfb48d0ee5f4ee69342137a3b21c09228362718055bc63eb58f67c69584c709bcba9193c1e094957d83ca6bbd393dd65ea3b5ab090c

Expected downloaded file to have size: 152981007
Computed size: 162396738

"Your callback function returned a promise which never resolved" error with cy.queryByText()

  • cypress-testing-library version: 2.3.6
  • node version: 10.12.0
  • npm (or yarn) version: 6.4.1

I have a few tests checking that an elements doesn't exist using a command like

cy.queryByText("xxxxxxx", { timeout: 300 }).should("not.exist");

Usually, everything is fine. But, occasionally, I get a failure like this:

     CypressError: cy.then() timed out after waiting '400ms'.

Your callback function returned a promise which never resolved.

The callback function was:

function Command__queryByText(thenArgs) {
              return commandImpl(thenArgs.document)
            }
      at Object.cypressErr (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:65283:11)
      at Object.throwErr (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:65248:18)
      at Object.throwErrByPath (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:65275:17)
      at http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:54007:21
      at tryCatcher (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:127195:23)
      at http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:122505:41
      at tryCatcher (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:127195:23)
      at Promise._settlePromiseFromHandler (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:125213:31)
      at Promise._settlePromise (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:125270:18)
      at Promise._settlePromise0 (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:125315:10)
      at Promise._settlePromises (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:125390:18)
      at Async._drainQueue (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:122119:16)
      at Async._drainQueues (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:122129:10)
      at Async.drainQueues (http://xxx.xxx.xxx:8084/__cypress/runner/cypress_runner.js:122003:14)
      at <anonymous>

I nailed it down to the timeout on https://github.com/kentcdodds/cypress-testing-library/blob/master/src/index.js#L53 , and everything seems to work if we remove the timeout option.

Since waitForElement is already called with a timeout option on https://github.com/kentcdodds/cypress-testing-library/blob/master/src/index.js#L24 , is it needed on the cypress command chain? Could it be removed from that line 53?

Sorry for not providing a code sample, but I have not been able to reliably reproduce it.

[solved] I get an error message if I don't prepend calls to findBy... with a get('body') call

  • cypress-testing-library version: ^6.0.0
  • node version: v10.21.0
  • npm (or yarn) version: 1.22.4 (yarn)

Relevant code or config

    cy.visit('/email-verified')
      .findByText(/okay/i)

What you did:

I visit a page and call findByText

What happened:

I get the following error message:

Timed out retrying: Expected container to be an Element, a Document or a DocumentFragment but got Window.

image

If I call get('body') before calling findByText it works:

    cy.visit('/email-verified')
      .get('body')
      .findByText(/okay/i)

Normalizer access within Cypress

  • cypress-testing-library version: 6.0.0
  • node version: 12.16.3
  • npm (or yarn) version: 6.14.4

Relevant code or config

 it('Manage Songwriters - Verify elements on page', () => {
        cy.visit('/songwriters/')
        cy.wait('@getWriters').then((xhr) => {
            const { objects } = xhr.responseBody as RootObject;
            }

        cy.get('.manage-writer-view > :nth-child(1) > #writer-list > li')
            .should('have.length', 10)
            .each(($writerList, index) => {
            const writer: Object  = objects[index]

       cy.wrap($writerList).within(() => {
                    cy.findAllByText(RegExp(writer.full_name, "i"),
                    {normalizer: getDefaultNormalizer({collapseWhitespace: true})} );
                
                    //iterate over each element within each `.songwriter`
               
                });

What you did:
Attempting to call getDefaultNormalizer from within the above script portion.

What happened:

Getting from my IDE:

Cannot find name 'getDefaultNormalizer'.

Reproduction repository:
N/A

Problem description:
Is this Normalizer call available via the cypress-testing-library? I don't see any documentation regarding this feature specific to Cypress. I have read https://testing-library.com/docs/dom-testing-library/api-queries#normalization . I'm hoping its a simple human error issue with the syntax I am using and this isn't a bug?

Suggested solution:
Extend access to this call within Cypress.

(TS) Type SelectorMatcherOptions is missing timeout

  • cypress-testing-library version: 3.0.1
  • node version: 10.13.0
  • yarn version: 1.13.0

Relevant code or config

cy.queryByText("foo", { timeout: 100 })

What you did:
Tried to change the value of the timeout option on queryByText.

What happened:
The test correctly waited for the set amount of time (100ms) but TS validation reports an error:
ctl-type-err

Problem description:
Queries using the SelectorMatcherOptions type are missing the type definition for the timeout option.

Suggested solution:
If this is not intentional, take the same approach as for MatcherOptions in #28 – update typings/index.d.ts.

How it is now:

import {
  SelectorMatcherOptions,
  Matcher,
  MatcherOptions as DTLMatcherOptions,
  getByTestId,
} from 'dom-testing-library'

export interface CTLMatcherOptions {
  timeout?: number
}

export type MatcherOptions = DTLMatcherOptions | CTLMatcherOptions

How it could be:


import {
  SelectorMatcherOptions as DTLSelectorMatcherOptions,
  Matcher,
  MatcherOptions as DTLMatcherOptions,
  getByTestId,
} from 'dom-testing-library'


export interface CTLMatcherOptions {
  timeout?: number
}

export type MatcherOptions = DTLMatcherOptions | CTLMatcherOptions
export type SelectorMatcherOptions = DTLSelectorMatcherOptions | CTLMatcherOptions

cy.findByText always returns true with should('not.exist')

  • cypress-testing-library version: 6.0
  • node version: 12.13.1
  • npm (or yarn) version: 6.13

Relevant code or config

cy.findByText('Non-existing Button Text').should('not.exist')

What you did:
Tried writing a test to assert non-existence. It always passes, even when the text exists.

What happened:

Reproduction repository:

https://github.com/coryhouse/cy-doesnt-exist-bug

To run:

npm install
npm run cy

Problem description:

This always passes, even when the text exists:

cy.findByText('Non-existing Button Text').should('not.exist')

Suggested solution:

Looks like cy.contains works fine for this use case, but would be great if the documented approach could work.

The engine "node" is incompatible with this module

  • cypress-testing-library version: 2.3.3
  • node version: 6.13.0
  • npm (or yarn) version: 1.10.1

Relevant code or config
see below

What you did:

$ npm install --save-dev cypress-testing-library
$ yarn install

What happened:
After running yarn install when cypress-testing-library was installed, I got the following message:

...
error [email protected]: The engine "node" is incompatible with this module. Expected version "> 6". Got "6.13.0"
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
...

Reproduction repository:
working on it

Problem description:
see above

Suggested solution:
The problem can be circumvented by running yarn install --ignore-engines but it seems like the solution would be to change the value of engines.node in package.json from "> 6" to ">6" since that's the format used in the relevant npm documentation.

Write Docs

We need to write documentation for this thing.

Revert changes to query*s and add deprecation warning

As noted in #108, we accidentally broke the query* queries. We should restore those to the original behavior and add a deprecation warning. Let's try to make it subtle enough to not be really annoying, but present enough to be noticed :)

Can't click on one of multiple elements returned by findAll

  • Cypress Testing Library version: 5.0.2
  • node version: 12.0.0
  • yarn version: 1.15.2

Relevant code or config:

cy.findAllByTestId("droppable").then(result => {
      // Convert to array because the result is a jQuery object, tried it as well without converting
      const resultArray = Array.from(result);
      resultArray[1].click({ force: true });
    });

What you did:

My issue is that I can't click on a single element returned by findAllByTestId. In my console, I can see that the query resolves to 2 DOM elements. When clicking either the first or the second, I see that the findAllByTestId query is executed, but the click command is not.

If I try clicking a nonexistent element from the array like resultArray[2], I do get an error that undefined cannot be clicked.

For context, the following does sort of work:

cy.findAllByTestId("droppable").click({multiple: true})

Using this snippet, I see that the first element was indeed clicked. As a result, both elements disappear and therefore I get an error that Cypress can't click the second. However, I don't want to click all elements, I want to click on just one of them.

What happened:

All commands in my test are executed except the click command (32 is findAllBy, 33 should have been the click command but is the next command).

image

Reproduction:

I tried reproducing but I couldn't get the Cypress suite to work in CodeSandbox.

Problem description:

See above.

Suggested solution:

I might be overlooking something but I don't find the docs very helpful at the moment: it lists one example of the combination of findAll with a user event, which I don't even think is valid code:

cy.findAllByText('Jackie Chan').click()

click() should in this case probably be click({multiple: true}) but an example showcasing my issue would be even more helpful I believe.

Thanks in advance! Hope I posted in the right place because I believe this has to do with the Cypress implementation and not with the findAll API.

Queries match elements inside the <head /> part of the document

  • cypress-testing-library version: 5.3.0

Relevant code or config

<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
    <h1>Hello world</h1>
  </body>
</html>
cy.findByText('Hello world')

What you did

Find an element by its text content.

What happened

Since the document title element in the head area also matches, the query tells me that it found more than one element with the expected text content.

Problem description

The queries are using the entire document as the container.

Suggested solution

Maybe the queries should use the body as the container. Elements in the head area cannot be interacted with and are generally not visible to the user. Except maybe for the title, but there should be more declarative ways to check for it than findByText.

Click on a disabled button with nested elements is silently ignored

  • cypress-testing-library version: 2.3.5
  • cypress version: 3.1.5
  • node version: 8.15
  • npm (or yarn) version: yarn 1.12.3

Note: This issue is related to getByText, but the problem is in the way it behaves in relation to cypress, not a bug in the actual getByText function itself.

Relevant code or config

<button disabled>
  <span>Hi</span>
</button>

What you did:

cy.getByText('Hi').click()

What happened:
The span element was clicked, even though the button was disabled. The click is ignored by the button though, since it is disabled.

Workaround:
You can revert to normal cypress commands and do this:

cy.contains('button', 'Hi').click();

Cypress will wait until the button is enabled before trying to click. Or if the timeout expires, it will throw an error.

Suggested solution:
I'm not sure? Silently failing seems like the wrong thing though. Perhaps I just shouldn't use cy.getByText to try to click on a button.

findAllByTestId failing on versions > 5.0.2

  • DOM Testing Library version: 5.1.1
  • node version: 11.4.0
  • npm (or yarn) version: npm: 6.13.1 yarn: 1.21.1

Relevant code or config:

cy.visit("/admin")
      .withConfig({})
      //.findAllByTestId("Get Started with the Building Directory app")
      .findAllByTestId("onboard-title-0")
      .should("be.visible")
      .and("contain", "Get Started")

What you did:

I am creating a set of tests here and few weeks ago this was passing fine. Now with an upgrade in package version, the 'findAllByTestId' is failing.

I rolled back versions of the cypress-testing-library so it seems this has been introduced as of Vr 5.1.1

What happened:

Screenshot 2020-01-30 at 12 01 59

Screenshot 2020-01-30 at 12 02 07

getAllBy* commands chained by should don't retry correctly

  • cypress-testing-library version: 2.3.3
  • node version: 8.12
  • npm (or yarn) version: 6.4.1

Relevant code or config

// I tried two ways to do this, both don't work
// cy.wait(100) // if I uncomment this, it will work
cy.getAllByText("hello").should('have.length.gte', 6)
cy.getAllByText("hello").should(($elements) => {
    expect($elements.length).to.be.gte(6)
})

What you did:
Run the above commands in an e2e test for an app (scenario for loading).

  1. the tested app first render nothing
  2. then it loads a few "hello" texts, but doesn't have as many as 6
  3. then it loads more than 6 "hello" texts

What happened:
the test fails

example

Reproduction repository:
I don't yet have one, will try to create when I have time.

Problem description:
getAllByText seems to first match 1 DOM, then it assumes getAllByText has already succeeded. When further should commands fail, cypress only retries those should commands, but not getAllByText. Therefore, although I verified that my DOMs have loaded before timeout, getAllByText is run only once and doesn't try to get them again.

Suggested solution:
I am not sure if this is a problem with cypress-testing-library or cypress itself. My only clue is that commands like get in cypress work with retry, so I assume it's a problem with this library. However, I couldn't find any information on cypress doc about this retry behavior, so I cannot really tell. I'd like some feedback.

[typescript] Cannot find name 'JQuery'

  • cypress-testing-library version: 5.0.2
  • node version: 12.13.0
  • npm (or yarn) version: (yarn) 1.19.1

What you did:
Installed @testing-library/cypress in monorepo root (yarn add -W -D @testing-library/cypress).

What happened:
Unrelated build failures in packages/ resulting in

../../../node_modules/@types/testing-library__cypress/index.d.ts:445:77 - error TS2304: Cannot find name 'JQuery'.

Reproduction repository:
https://github.com/a-b-r-o-w-n/testing-library-cypress-bug
https://github.com/a-b-r-o-w-n/testing-library-cypress-bug/runs/303541569

How to test disappearance?

  • cypress-testing-library version: 2.2.0
  • node version: 9.4.0
  • yarn version: 1.7.0

Relevant code or config

// I have a table with users, and I want to test user deletion
cy.getByTestId(`user-id-${userId}`).within(() => {
  cy.getByText('Remove').click();
});
cy.getByTestId(`user-id-${userId}`).should('not.exist');

What you did:
I've tried to use cypress-testing-library custom commands with should('not.exist') expectation.

What happened:
The expectation failed, because cypress does not wait until the row/element disappeared.

On the other hand the following works as expected:

cy.getByTestId(`user-id-${invitee.userId}`).within(() => {
  cy.getByText('Remove').click();
});
cy.get(`[data-testid="user-id-${invitee.userId}"`).should('not.exist');

What would be the proper way to test element disappearance with custom commands?

cy.within support

  • cypress-testing-library version: 2.0.0
  • node version: 8.4.0
  • npm version: 5.3.0

Relevant code or config

cy
  .getByLabelText("Label text")
  .getFormByTitle("Form title") // custom command
  .within(() => {
// select editor with the same label as the previous getByLabelText, but nested in the form
    cy.getByLabelText("Label text") 
  })

Philosophy

There's nothing to guarantee that label texts are unique within the page. Users will be filling out a form one section at a time. The form can have a title to indicate to the user what they should be filling in, while the label texts themselves are no different to another form with a different title.

So to mimic how the user would fill in the page, you'd look for the form with that title and look for label texts within that form section.

Problem description:

Cypress supports a within function. All cy statements within the within function scope should use its subject as the container.

Currently, cypress-testing-library always uses the window.document as container.

Suggested solution:

Check cy.state("withinSubject") (Cypress source) to check whether the query is being executed within a within function scope and use it instead of doc as container parameter to query functions.

Unhelpful error messages for query* commands

  • cypress-testing-library version: 5.1.0

Relevant code or config

Test

cy.queryByLabelText('Test 1').click()
cy.queryByLabelText('Test 2').click()
cy.queryByLabelText('Test 3').click()
cy.queryByLabelText('Test 4').click()

HTML

Passing - no issues
<label for="1">Test 1</label>
<input id="1" />

Failing - couldn't find the label element
<label for="2">Test Oops</label>
<input id="2">

Failing - there is no `for` attribute on the label element
<label>Test 3</label>
<input id="3" />

Failing - couldn't find the input element
<label for="4">Test 4</label>
<input />

What happened:

The first passes fine. The consoleProps do not have the same description level as built-in Cypress commands

The second fails, but not as expected. The issue is the label element could not be found by the text "Test 2"

The third fails, but not as expected. The issue is the label element doesn't have a for attribute and has no way to associate with an input

The fourth fails, but not as expected. The issue is the label element has no corresponding input element.

All failures result in this error message:

CypressError: cy.click() failed because it requires a DOM element.

The subject received was:

  > {}

The previous command that ran was:

  > cy.then()

Error image described by code block

Note that the failure is on the cy.click command and not the queryByLabelText command. This is because https://github.com/testing-library/cypress-testing-library/blob/master/src/index.js#L87 simply wraps any returned value in an jQuery wrapper. It seems to be returning an empty object rather than an empty NodeList which Cypress automatically detects.

Also notice the error mentions the previous command was cy.then, even though that command wasn't actually used anywhere in user code. This is confusing. This is because of https://github.com/testing-library/cypress-testing-library/blob/master/src/index.js#L84 (use of cy.window().then()

There is also a comment about Promises not working with Cypress retryability which is not accurate. The problem probably comes from the use of cy.then. The original intent of Cypress Custom commands was not to use any cy commands at all. Internal Cypress Commands do not use them. Here's the source code for all the traversal-style commands: https://github.com/cypress-io/cypress/blob/develop/packages/driver/src/cy/commands/traversals.coffee. Notice promises are used in there just fine.

Problem description:
Failures to find elements returned from @testing-library/dom are unhelpful and confusing

Suggested solution:
Refactor the use of Cypress Custom Commands a bit to better handle not finding an element and remove the use of cy.window() and cy.then. Cypress has a cy.state function and it saves the window in cy.state('window') which is synchronously resolved.

Also try some of the query commands with known failures and see if the errors are useful. This goes a long way to guiding developers to finding out why something went wrong.

Typescript setup is more difficult than it has to be

Problem description:
If a project is set up to use Typescript with Cypress, an additional step is required for Typescript to understand the custom commands. The Readme shows the additional step required to be added to the tsconfig.json.

This is because the DefinitelyTyped package is defining type definitions for the module @testing-library/cypress, but to add commands at runtime, you must import @testing-library/cypress/add-commands which does not have a type definition associated.

Suggested solution:
2 solutions:

  1. Add commands to Cypress when the developer adds import @testing-library/cypress
  2. Update type definitions to include the add-cypress path.

The 2nd solution doesn't involve this repository and would not be a risk of a breaking change (other than possibly removing the line about the additional setup).

getByDisplayValue is missing in TypeScript types

  • cypress-testing-library version: 3.0.1
  • node version: 11.10.0
  • yarn version: 1.14.0

Relevant code or config

cy.getByDisplayValue("something");

What you did:
updated to cypress-testing-library 3.0.1 and because of breaking changes in dom-testing-library as outlined in the release notes, I switched my getByValue queries to getByDisplayValue.

What happened:
TS compile fails because getByDisplayValue is not defined in cypress-testing-library/typings

Suggested solution:
update typings to reflect the changes in the API

support for cypress v4

  • cypress-testing-library version: v5.2.1
  • node version: v10.19.0
  • npm (or yarn) version: v6.13.4

Relevant code or config

"cypress": "^2.1.0 || ^3.0.0"

What you did:

installed v4.0.0 of cypress and ran npm ls

What happened:

slightly different versions in this project, but was the first i found with public logs: https://travis-ci.com/travi-org/theme-components/builds/147829710#L301-L313

Reproduction repository:

travi-org/theme-components#4

Problem description:

the peer ranges defined as compatible for cypress do not include v4.0.0 that was released today: https://docs.cypress.io/guides/references/changelog.html#4-0-0

Suggested solution:

add ^4.0.0 to the allowed peer ranges:

"cypress": "^2.1.0 || ^3.0.0" 

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The push permission to the Git repository is required.

semantic-release cannot push the version tag to the branch master on remote Git repository with URL https://github.com/kentcdodds/cypress-testing-library.git.

Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment and make sure the repositoryUrl is configured with a valid Git URL.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Chained cypress-testing-library commands don't work as expected

  • cypress-testing-library version: 6.0.0
  • node version: 12.14.1
  • npm (or yarn) version: yarn 1.21.1

Relevant code or config

cy.findAllByTestId('test-id').findByText('mytext').parents('.parent');

What you did:
I want to chain commands from cypress-testing-library, so that they are executed in the same context. In the example above I want to retrieve the element which contains the text "mytext" but only for elements which have a parent (somewhere in the upper DOM) with a data-testid attribute with the value 'test-id'.

What happened:
The command doesn't find an element with the given text, even if there would be such an element (proof is being provided in the Hint below).

image

Hint:

If I run the same code as above, but with a contains instead of the findByText everything works as expected:

cy.findAllByTestId('test-id').contains('mytext').parents('.parent');

image

Thanks for this library and the whole testing-library family in general! Cheers!

Error with version 3.16.6 of dom-testing-library

  • cypress-testing-library version: 2.3.6
  • node version: 10.4.0
  • npm (or yarn) version: yarn v1.13.0

Relevant code or config

    cy.getByText('Button Text').click()

What you did: yarn test

What happened:

TypeError: container.matches is not a function
      at queryAllByText (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:1665:31)
      at getAllByText (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:1876:15)
      at firstResultOrNull (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:1988:18)
      at getByText (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:1886:46)
      at Object.assign.container.container (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:438:28)
      at onMutation (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:2098:24)
      at Promise (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:2114:5)
      at Promise (<anonymous>)
      at waitForElement (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:2074:10)
      at baseCommandImpl (http://localhost:4101/__cypress/tests?p=cypress/support/index.js-916:437:54)

Reproduction repository: n/a

Problem description: This seems to be an issue with using [email protected]. I installed specifically [email protected] (the exact version specified in cypress-testing-library/package.json), and manually replaced the dom-testing-library used in cypress-testing-library/node_modules with the older version, and this fixed the issue.

Suggested solution: Specify to use exactly version 3.12.4 of dom-testing-library, or whichever newest one does not provide this error.

TL enforces cypress 4.0.1

  • cypress-testing-library version: 5.3.0
  • node version: 2.14.0
  • npm (or yarn) version: yarn 1.21.1

Relevant code or config
package.json

{
  "name": "cypress-example-docker-gitlab",
  "version": "1.0.0",
  "description": "> Cypress + Docker + GitLabCI = ❀️",
  "main": "index.js",
  "private": true,
  "scripts": {
    "test": "cypress run"
  },
  "repository": {
    "type": "git",
    "url": "git+ssh://[email protected]/cypress-io/cypress-example-docker-gitlab.git"
  },
  "keywords": [
    "cypress",
    "cypress-io",
    "example",
    "gitlab"
  ],
  "author": "[email protected]",
  "license": "ISC",
  "bugs": {
    "url": "https://gitlab.com/cypress-io/cypress-example-docker-gitlab/issues"
  },
  "homepage": "https://gitlab.com/cypress-io/cypress-example-docker-gitlab#README",
  "devDependencies": {
    "cypress": "3.8.3",
    "@testing-library/cypress": "^5.3.0"
  }
}

What you did:
I cloned the cypress gitlab example and added the testing library cypress dependency (as seen in the package.json above) and bumped the cypress version to 3.8.3. I then run cypress in a docker container:
docker run --rm -it -v /<path to repo>/:/<new dir>/ cypress/browsers:node12.14.0-chrome79-ff71 bash
What happened:
While doing yarn inside the container I receive an error! Apparently, yarn tries to install two versions of Cypress (3.8.3 and 4.0.1). I remove the TL dependency the error disappears. Not sure whether this expected behaviour or whether the provided peerDependency in TL should handle this?

 The Cypress App could not be downloaded.

Does your workplace require a proxy to be used to access the Internet? If so, you must configure the HTTP_PROXY environment variable before downloading Cypress. Read more: https://on.cypress.io/proxy-configuration

Otherwise, please check network connectivity and try again:

----------

URL: https://download.cypress.io/desktop/4.0.1?platform=linux&arch=x64
Error: Corrupted download

Expected downloaded file to have checksum: 7e26904b56c560f9ba893085903b8435c651a86058b4ba81075f51158e4846e884a039c473d07ce74ef93ab8134164e8fe6eac192a8fababe99fc13ce757310e
Computed checksum: 12c7e488d3ff1f7452979b64972d7ed3b12ca127f2f388abdf816660509fa37034aae50256d91da0affb9eeefaad4fd01eff07e60839e15513516c4af02f869a

Expected downloaded file to have size: 167819701
Computed size: 167819701

----------

Platform: linux (Debian - 9.11)
Cypress Version: 4.0.1
The Cypress App could not be downloaded.

Does your workplace require a proxy to be used to access the Internet? If so, you must configure the HTTP_PROXY environment variable before downloading Cypress. Read more: https://on.cypress.io/proxy-configuration

Reproduction repository:

https://gitlab.com/cypress-io/cypress-example-docker-gitlab

TypeScript: invoke doesn't see jQuery methods

Using invoke raises an error when trying to use jQuery methods.

Here's an example:

cy.getByTestId('input')
  .invoke(
    'data',
    'isactive',
  )
  .should('eq', true);

This is the error:

Argument of type '"data"' is not assignable to parameter of type '"dir" | "slot" | "style" | "title" | "accessKey" | "accessKeyLabel" | "autocapitalize" | "draggable" | "hidden" | "innerText" | "lang" | "offsetHeight" | "offsetLeft" | "offsetParent" | ... 227 more ... | "focus"'.

It appears the return type of getByTestId is still evaluating to HTMLElement.

I'll look into this when I get time.

Incorrect TypeScript return types from commands

  • cypress-testing-library version: 2.4.0
  • node version: 10.15.3
  • npm (or yarn) version: 6.4.1

Relevant code or config

cy.getByTestId('activation-url').should(element => {
  expect(element.tagName).not.to.equal(undefined);
});

What you did:

According to https://github.com/kentcdodds/cypress-testing-library/blob/master/typings/index.d.ts#L70-L73 element should be a regular HTMLElement if no other type is provided.

What happened:

The test fails because element is a JQuery object and not an HTMLElement.

Problem description:

The return type of getByPlaceholderText should be Chainable<JQuery<E>> as per https://github.com/cypress-io/cypress/blob/develop/cli/types/index.d.ts#L724

Suggested solution:

Update TypeScript typings to correctly match actual return values.

Typings aren't included in built package

  • cypress-testing-library version: 2.3.0

What you did: Install cypress-testing-library v2.3.0

What happened: No types are present in node_modules/cypress-testing-library folder

Problem description: kcd-scripts build requires files to be in src

Suggested solution: Move typings to src and update package.json like so: "typings": "dist/typings"

regex selector does not appear in cypress left panel

  • cypress-testing-library version: 2.3.4
  • node version: 8.14.0
  • npm version: 6.5.0

Relevant code or config

    cy.queryByText(/basic/i).click(); // displays QUERYBYTEXT
    cy.queryByText("confirm").click(); // displays QUERYBYTEXT confirm

Problem description:
I guess this issue doesn't concern specifically a type of query, but rather its integration with cypress:
When using a regex to select any DOM element, I don't see the corresponding regex in the cypress panel, contrary to when I use a text selector.

querybytext-text vs regex

is it the expected behaviour? (Then why?)
Otherwise I would be delighted to try to fix the problem.

Suggested solution:
Display the stringified regex.

Allow to change query timeout.

  • cypress-testing-library version: 2.0.0
  • node version: 8.4.0
  • npm version: 5.3.0

Problem description:

Currently, the timeout for queries is hard-coded to 3000:
https://github.com/kentcdodds/cypress-testing-library/blob/master/src/index.js#L11

When I visit my app, it shows a loading indicator, which takes more than 3 seconds. I can add a cy.wait to make things work, but if the website gets faster, that wait just slows everything down. So I'd like to be able to configure the timeout as an option to the query functions.

Suggested solution:

Destructure the last option in the command function {timeout, ...args} and use it in waitForElement, like timeout: timeout || 3000.

I'll create a PR this weekend.

Add autocomplete support for the should(chainer, ...) variants

Environment:

  • cypress-testing-library version: 5.3.0
  • node version: 12.13.1
  • npm (or yarn) version: 6.12.1
  • typescript version: 3.7.4
  • Intellij Ultimate version: 2019.3.3

Relevant code or config:

  // ts.config
  "compilerOptions": {
    "strict": true,
    "baseUrl": "../node_modules",
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "@types/testing-library__cypress"],
    "noEmit": false
  },
// support/index.ts
import "@testing-library/cypress/add-commands";

What you did:

cy.findAllByText('"Some text').should('have.length', 2);

What happened:

image

You get a warning and no autocompletion. The code runs just fine.

Problem description:

When using the cy.get().should()-syntax in Cypress, you get autocompletion for all the "chainer" variants (as in should("chainer")). Using e.g cy.findByText().should() from CTL will not only give you a linter warning, but also no autocompletion.

Suggested solution:

If there is an existing solution to this issue, please add it to the readme. Alternatively: perhaps it would be possible to add the Typescript definitions for each should-variant as they have done for the original cy.get().should()-variants?

Property 'configureCypressTestingLibrary' does not exist on type 'cy & EventEmitter'

  • cypress-testing-library version: 6.0.0
  • node version: 10.18.1
  • npm (or yarn) version: npm v6.13.4

Relevant code or config

FWIW I tried installing @types/testing-library__cypress v5.0.6 (even though it was already in node_modules).
Here's my tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "baseUrl": "../node_modules",
    "outDir": "./ConvertedJSFiles",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "cypress",
      "@types/testing-library__cypress"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "include": [
    "**/*.*"
  ],
  "exclude": [
    "node_modules",
    "cache"
  ]
}

What you did:

I enabled javascript checking via checkJs in tsconfig.json and invoked cy.configureCypressTestingLibrary in cypress/support/index.js

What happened:

Typescript is telling me Property 'configureCypressTestingLibrary' does not exist on type 'cy & EventEmitter'.

Many of my custom commands weren't recognized as being members of Cypress.Chainable and adding their definitions to commands.d.ts fixed it, and now configureCypressTestingLibrary is the only one giving me trouble. It looks like it's because it's missing from the type definitions.

Setting `defaultCommandTimeout` in cypress.json is not applied

  • cypress-testing-library version: 2.3.1
  • node version: 9.0.0
  • npm (or yarn) version: 1.10.1

Relevant code or config

        cy.visit("/")
            .getByTestId("signUpButton", {timeout: 6000})

What you did:
I wanted to select a few elements, with a longer timeout. After a few selects, I figured it would be just easier to set the default command timeout in cypress.json, so I don't have to set this every time I call getBy... methods. So I went to cypress.json and put "defaultCommandTimeout": 6000.

What happened:
The default 6000ms command timeout wasn't applied.

Suggested solution:
I guess we should modify the defaults object (https://github.com/kentcdodds/cypress-testing-library/blob/master/src/index.js#L5):

var defaults = {
  timeout: Cypress.config().defaultCommandTimeout
};

Support running commands against the previous yielded subject

I'm converting #100 by @tlrobinson to an issue. cc @twgraham, @intelligentspark, and @NicholasBoll.

Here's the original PR's comment (to save you a click)

What:

Changes the custom Cypress commands to respect the previously yielded subject, for example, with the following document:

    <button>Button Text 1</button>
    <div id="nested">
      <button>Button Text 2</button>
    </div>

this

cy.get('#nested').findByText('Button Text 1').should('not.exist')

would previously fail because findByText was not passed the result of cy.get('#nested') as its container (defaulting to document)

Why:

It's a convenient way to scope commands to the result of a previous command, and for users of builtin Cypress commands it's surprising that @testing-library/cypress doesn't currently behave like this.

How:

The prevSubject option is now passed to Cypress.Commands.add() (with a value of ['optional', 'document', 'element', 'window'] which matches builtin commands like contains. This causes the subject (if any) to be passed as the first argument to the command. The subject is given lower precedence than the testing-library's container option, but higher precedence than the document itself.

Checklist:

  • Documentation N/A
  • Tests
  • Ready to be merged

Merging #100 caused a breaking change (#109). I've reverted it (0b73b69) and now we need to discuss whether we want to make this change and whether it's possible to solve the originally stated problem in the PR and have the testing style mentioned in #109.

`cy.findByText(...).should('not.exist')` returns true for non-selected dropdown option

  • cypress-testing-library version: 6.0.0
  • node version: 12.18.2
  • npm (or yarn) version: (yarn) 1.22.4

This issue (in a way) builds on top of @coryhouse's issue #135 cy.findByText always returns true with should('not.exist')

I've forked the repo and added the new failing test to master:
https://github.com/vfonic/cy-doesnt-exist-bug

Repro steps: clone, npm i, npm run cy

You can also see the commit diff:
vfonic/cy-doesnt-exist-bug@7cf22ca

Ok, I just made one more commit:
coryhouse/cy-doesnt-exist-bug@master...vfonic:master

(There's "Learn React" a tag below that gets correctly selected when the above elements are missing.)

Basically, findByText returns the first DOM element by that text.
should('not.exist') returns true ("it doesn't exist") if the element is hidden or non-selected dropdown option.

I'm not sure if this is cypress-testing-library issue or cypress/chai issue?
It just sounds misleading, especially for the second case (when findByText finds select option)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.