【问题标题】:TS2339: Property 'dayjs' does not exist on type 'Cypress & EventEmitterTS2339:“Cypress 和 EventEmitter”类型上不存在属性“dayjs”
【发布时间】:2021-03-25 19:16:32
【问题描述】:

我最近重构了我的代码以使用 dayJS 而不是 Moment.js,现在 Webstorm 报告了大量 TS2339 错误。这些错误并没有阻止我的代码编译或运行,但它使查找 实际 错误变得非常困难。下面是一些出现错误的代码示例:

export function verifyCreatedDate(date: string) {
  cy.log('Verify item creation date');
  cy.get('[data-cy="timeline-date"]').should(
    'have.text',
    Cypress.dayjs(date).format('MM/DD/YY'),
  );
}

这是我的tsconfig.json 文件:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": false,
    "module": "es2015",
    "target": "es2015",
    "jsx": "react",
    "allowJs": true,
    "types": ["cypress", "@percy/cypress"],
    "moduleResolution": "node",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"]
  },
  "include": ["**/*.ts", "node_modules/cypress/types/mocha/index.d.ts"]
}

我尝试将 dayJS 添加到 "types""include" 部分,然后重新启动 WebStorm,但这也没有解决错误。我一直在寻找这个问题的答案大约一个星期,虽然这是一个常见问题,但我发现的建议解决方案都没有奏效。

最后,这是我的support/index.js 文件的相关部分:

// if multiple specs need to use dayjs import it in the support file
// and add to the global Cypress object
const dayjs = require('dayjs');

Cypress.dayjs = dayjs;

【问题讨论】:

  • 您是否尝试添加将dayjs 添加到Cypress 命名空间的d.ts 垫片,类似于通常使用自定义命令(docs.cypress.io/guides/tooling/…)所做的?
  • 我一直在看这个,但我很难弄清楚如何在 dayJS 中添加。说明完全侧重于在定义函数的位置添加自定义命令,如何使用此方法将 DayJS 之类的模块添加到命名空间?
  • 为什么要将 dayjs 附加到 Cypress 对象?你可以在你需要的文件中导入/要求它吗?
  • 我们几乎在每个规范中都使用 dayJS - 在这种情况下,文档建议将其附加到 Cypress 对象

标签: typescript webstorm cypress dayjs


【解决方案1】:

cypress/support/index.d.ts:

/// <reference types="cypress" />

declare namespace Cypress {
    interface Chainable {
        ... your custom commands

    }

    import dayjs from 'dayjs';
    interface Cypress {
        dayjs: dayjs.Dayjs;
    }
}

【讨论】:

    【解决方案2】:

    你在搞乱的是扩展类型,就像你对命令一样添加:https://docs.cypress.io/guides/tooling/typescript-support#Types-for-custom-commands

    declare namespace Cypress {
      interface Cypress {
        dayjs: any;
      }
    }
    

    【讨论】:

    • 为什么使用any?你失去了所有 IntelliSense 的东西。我尝试了dayjs: Dayjs;,但importsuport/index.d.ts 文件中甚至中断了以前工作的自定义命令的自动完成。
    猜你喜欢
    • 2016-03-14
    • 2017-02-25
    • 2021-11-24
    • 2019-01-11
    • 2021-05-08
    • 2021-10-15
    • 2020-12-13
    • 2021-08-04
    • 2020-07-01
    相关资源
    最近更新 更多