【问题标题】:How to correctly export and import functions for cypress plugin index.ts?如何正确导出和导入 cypress 插件 index.ts 的函数?
【发布时间】:2022-03-08 21:16:34
【问题描述】:

我正在开发 plugin/index.ts 文件,我在其中放置异步函数,例如。清除数据库或将文件上传到应用程序,但它开始增长,我想办法让它保持干净和结构化。

this 视频中,我看到有一种方法可以将函数存储在单独的文件中,然后使用module.exports = { function } 导出它们,然后在index.ts 中使用require 导入它们。

但我不能让它适用于我的情况。

这是我的plugins/index.ts 文件的简单形式:

const uploadDocument = require('./documents');

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

  on('task', {
    clearDatabase: clearDatabase,
    uploadDocument: uploadDocument,
  });
  
  async function clearDatabase() { ... }
}

我决定将函数uploadDocument的代码移动到plugins/documents.ts文件中:

这就是文件plugins/documents.ts 的样子:

imports...

async function uploadDocument(fileName: string) { ... }

module.exports = { uploadDocument }

当我以这种方式运行任务测试时:

cy.task("uploadDocument", 'Very_light_file.pdf')

我在 Cypress 中收到此错误:

【问题讨论】:

    标签: javascript node.js typescript cypress


    【解决方案1】:

    看起来问题出在你的 module.exports 和 import 上。

    试试这个,

    // document.ts
    
    export async function uploadDocument(fileName: string) { ... }
    // module.exports = { uploadDocument }
    
    // plugins/index.ts
    
    import { uploadDocument } =  from './documents'
    

    【讨论】:

      【解决方案2】:

      从帖子中,我可以看出 TS 是混合 JS 那里。例子是JS,你用的是TS,所以没有module.exports。

      试试纯 JS 版本,以后再转成 TS。

      【讨论】:

      • 你是对的!谢谢你的提示!我试图以错误的方式导出函数。
      【解决方案3】:

      如果您查看cypress-io/cypress-realworld-app/blob/develop/cypress/plugins/index.ts,您会发现他们将module.exports 更改为:

      // cypress/plugins/index.ts
      
      export default (on, config) => {
        config.env.defaultPassword = process.env.SEED_DEFAULT_USER_PASSWORD;
        config.env.paginationPageSize = process.env.PAGINATION_PAGE_SIZE;
        // Auth0
        //
        //
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 2021-08-10
        • 2016-08-31
        • 2021-05-19
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 2018-06-10
        相关资源
        最近更新 更多