Cypress - how to find by text content?

≯℡__Kan透↙ 提交于 2020-12-29 05:15:43

问题


In Cypress, I want to select a button from a group of buttons based on its text-content. How can I do it? Here is my approach:

export const getCustomerButton = () => getNavigationSidenav()
  .find('mat-expansion-panel-header')
  .each(($el, index, $list) => {
    const text = $el.find('.mat-content > mat-panel-title').text();
    if (text === 'Customer') {
      return $el;
    }
    return null;
  });

The problem I have now is that I have to filter out the nulls from the element array. Is there a less complicated way?


回答1:


This will yield the DOM element with YOUR_BUTTON_CLASS which contains text 'Customer'. Is that what you're looking for?

cy.get('YOUR_BUTTON_CLASS').contains('Customer');

Here the documentation for .contains cypress command.




回答2:


Or maybe an even slicker solution is to use this:

cy.contains('YOUR_BUTTON_CLASS', 'Customer');

This can be done since contains() can hold 2 arguments. And if it gets two arguments the first one is always the element and the second the text.




回答3:


Another option that's not mentioned in the previous answers here.

Use testing-library/cypress-testing-library

After the installation, just import it in cypress' commands.js:

import '@testing-library/cypress/add-commands'

And in your tests

cy.findAllByText("Jackie Chan").click();
cy.findByText("Button Text").should("exist");
cy.findByText("Non-existing Button Text").should("not.exist");
cy.findByLabelText("Label text", { timeout: 7000 }).should("exist");
cy.get("form").within(() => {
  cy.findByText("Button Text").should("exist");
});
cy.get("form").then((subject) => {
  cy.findByText("Button Text", { container: subject }).should("exist");
});

This is pretty straightforward and easy to use. We use this in our production site along with react testing library. Highly recommend :)



来源:https://stackoverflow.com/questions/57533756/cypress-how-to-find-by-text-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!