检查输入字段是否为空或在 Cypress 测试中无法正常工作

Check if an input field is empty or not is not working properly in Cypress tests

我在 Cypress 中得到了 2 个步骤定义,用于检查输入字段是否为空(取决于我如何构建我使用 RegEx 设置的句子)。

首先我的问题是,cypress 说测试失败是因为输入字段是空的,而实际上它不是。

我定义的步骤:

/** We check if the input field with the given name is empty */
Given(/^The input field "(.*)" is (not )?empty$/, (inputFieldName, negation) => {
  if (negation === 'not ') {
    CypressTools.getByName(inputFieldName).should('not.be.empty');
  } else {
    CypressTools.getByName(inputFieldName).should('be.empty');
  }
});

/** We check if the input field with the given name is visible and empty */
Given(/^The input field "(.*)" is visible and empty$/, (inputFieldName) => {
  CypressTools.getByName(inputFieldName).should('be.visible').should('be.empty');
});

在我的特定测试中,cypress 应该检查一个值填充的输入字段,并且步骤定义如下: 输入字段“XYZ”不为空

我可以看到,if 条件运行良好,因此定义或 RegEx 站点上没有问题。 但是测试失败了,因为赛普拉斯说输入字段是空的,但事实并非如此。

我怀疑 Cypress 会测试输入字段中输入标签之间的值,但不会检查输入标签中的值属性。

至少,我尝试在步骤定义中添加一个 invoke('val')

CypressTools.getByName(inputFieldName).invoke('val').should('not.be.empty');

它适用于第一步定义,但是当我也为第二步定义这样做时,柏树测试失败并告诉我:

Timed out retrying: You attempted to make a chai-jQuery assertion on an object that is neither a DOM object or a jQuery object.
The chai-jQuery assertion you used was:
  > visible
The invalid subject you asserted on was:
  > 
To use chai-jQuery assertions your subject must be valid.
This can sometimes happen if a previous assertion changed the subject.

我不明白这里的问题。此方法对 invoke() 是否有效,或者是否有更好的解决方案来涵盖所有情况?

非常感谢您的帮助。

您的错误消息指出的问题是沿着命令链传递的主题不适合下一步,

CypressTools.getByName(inputFieldName)
  .invoke('val')                      // changes subject to the text of the input
                                      // (not a DOM element)
  .should('be.visible')               // needs a DOM element
  .should('not.be.empty');

最可靠的解决方法是将测试分为两步

CypressTools.getByName(inputFieldName).should('be.visible');

CypressTools.getByName(inputFieldName)
  .invoke('val')
  .should('not.be.empty');

但我认为简单的重新排序也可以

CypressTools.getByName(inputFieldName)
  .should('be.visible')              // check the DOM element, passes it on as subject
  .invoke('val')                     // changes subject to the text of the input
  .should('not.be.empty');           // check the text is not empty