TypeScript 中的 Cypress:Mocha afterEach:如果 currentTest 失败则停止 Runner

Cypress in TypeScript: Mocha afterEach: Stop Runner if currentTest failed

目标是如果任何测试失败停止 Cypress runner,并且这些 Mocha 测试是用 TypeScript 编写的。下面的 Mocha afterEach() 有两个问题...

/// <reference types="Cypress" />

  afterEach(() => {
    if (this.currentTest.state === 'failed' && 
      this.currentTest._currentRetry === this.currentTest._retries) {
      Cypress.runner.stop();
    }
  });

问题如下:

  1. this.currentTest.* >>> 参考 this >>> TS2532: Object is possibly 'undefined'
  2. Cypress.runner.stop() >>> TS2339: Property 'runner' does not exist on type 'Cypress'

如何在 TypeScript 中解决这个问题并使用 // @ts-ignore 忽略它?

谢谢,感谢帮助。

是的,您可以使用 // @ts-ignore 。此外,您还需要使用常规函数 () {} 语法,而不是 lambda“粗箭头”语法 () => {}

参考赛普拉斯文档 : https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Avoiding-the-use-of-this

Accessing aliases as properties with this.* will not work 
if you use arrow functions for your tests or hooks.  This is why all of our
examples use the regular function () {} syntax as opposed to the
lambda “fat arrow” syntax () => {}.

代码看起来像这样

afterEach(function() {
    if (this.currentTest.state === 'failed' && 
      //@ts-ignore
      this.currentTest._currentRetry === this.currentTest._retries) {
      //@ts-ignore
      Cypress.runner.stop();
    }
  });