简体   繁体   English

Cypress + Dom 测试库:getByText 找不到输入的值

[英]Cypress + Dom Testing Library: getByText does not find input's value

I'm using Cypress with Cypress Testing Library to test my React application.我正在使用 Cypress 和Cypress 测试库来测试我的 React 应用程序。

I have an input with a name ('Steve') as its value and I'm trying to find it with cypress like this:我有一个名称('Steve')作为它的值的输入,我试图用这样的柏树找到它:

// In the component:
<input defaultValue="steve" />

// In the spec file:
cy.getByText(/steve/i).should('exist');

But Cypress does not find this element and the test fails.但是 Cypress 没有找到这个元素,测试失败。 If I change the input to a div:如果我将输入更改为 div:

<div>Steve</div>

it works (but I need to render an input).它有效(但我需要呈现输入)。 How can Cypress (and Dom Testing Library) find input's values? Cypress(和 Dom 测试库)如何找到输入的值?

I found the answer.我找到了答案。 getByText() does not find values of <input /> . getByText()找不到<input />值。 getByDisplayValue() does. getByDisplayValue()确实如此。 I don't like that, because that makes it a little dependent on implementation details, but at least this fixes the tests.我不喜欢那样,因为这使得它有点依赖于实现细节,但至少这修复了测试。

You can identify the element without mounting the react component.您可以在不安装反应组件的情况下识别元素。 If you are testing your react app in isolation with the source code or writing functional UI test cases, you can consider a Cypress plugin called cypress-react-selector .如果您正在与源代码隔离测试您的 React 应用程序或编写功能性 UI 测试用例,您可以考虑使用名为cypress-react-selector的 Cypress 插件。 It helps you identify web elements by component, props, and state even after the minification.即使在缩小之后,它也可以帮助您通过组件、道具和状态来识别 Web 元素。 You need to use React Dev Tool to identify the component names in that case.在这种情况下,您需要使用 React Dev Tool 来识别组件名称。

Here is an example:下面是一个例子:

Suppose your react app:假设您的反应应用程序:

const MyComponent = ({ someBooleanProp }) => (
  <div>My Component {someBooleanProp ? 'show this' : ''} </div>
)

const App = () => (
  <div id='root'>
    <MyComponent />
    <MyComponent someBooleanProp={true} />
  </div>
)

ReactDOM.render(<App />, document.getElementById('root'))

Then you can simply identify the react element like:然后你可以简单地识别反应元素,如:

cy.react('MyComponent', { someBooleanProp: true })

So, you can try something like:因此,您可以尝试以下操作:

cy.react('Input',{defaultValue:"steve"}).should('exist');

Find more sample test here 在此处查找更多示例测试

Hope it will help!希望它会有所帮助!

Because getByText() method always returns the value of innerText and that is why when you specify <div defaultvalue='XYZ'/> , it doesn't work.因为 getByText() 方法总是返回 innerText 的值,这就是为什么当您指定<div defaultvalue='XYZ'/> ,它不起作用。

You can check this out in DevTools console as well...您也可以在 DevTools 控制台中查看此内容...

<div id='name'>XYZ</div>
document.getElementById('name').innertText will return you XYZ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM