Cypress – 使用嵌套函数而不是使用 while 循环

huangapple go评论60阅读模式
英文:

Cypress - nested function instead of using while loop

问题

我注意到当我使用 while 循环时,Cypress 不起作用,所以我找到了这种解决方案:

const functionName = () => {
  if (a != b) {
    this.functionName();
  } else {
    cy.get(".selector").click();
  }
};

这段代码(TypeScript)运行得非常好,但 'this' 会被标记为红色,并出现消息:"Object is possibly 'undefined'."

有没有办法消除这个错误?

英文:

I spotted that when I'm using while loop, cypress does not work, so instead of while loop I found this kind of solution:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const functionName = () =&gt; {
  if ( a != b ) {
    this.functionName();
  } else {
    cy.get(&quot;.selector&quot;).click()
  }
};

<!-- end snippet -->

This block of code (typescript) works really well, but 'this' is highlighted in red and the message appears: "Object is possibly 'undefined'."

Any idea how can I to get rid off this error?

答案1

得分: 1

假设这是一个 TypeScript 错误,请添加[非空断言运算符](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)

```ts
// 使用 --strictNullChecks 编译
function validateEntity(e?: Entity) {
  // 如果 e 为 null 或无效实体,抛出异常
}
function processEntity(e?: Entity) {
  validateEntity(e);
  let s = e!.name; // 断言 e 非空并访问 name
}

参考如何抑制“错误 TS2533:对象可能为'null'或'undefined'”回答了相同的问题。

你可能不需要 this. 前缀,因为该函数在当前作用域中定义(不是类方法)。


<details>
<summary>英文:</summary>

Assuming it&#39;s a typescript error, add the [Non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)

```ts
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
  // Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
  validateEntity(e);
  let s = e!.name; // Assert that e is non-null and access name
}

For reference, How to suppress "error TS2533: Object is possibly 'null' or 'undefined'" answers the same question.

You probably don't need the this. prefix at all, since the function is defined on the current scope (not a class method).

huangapple
  • 本文由 发表于 2023年2月16日 17:38:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定