如何正确导出和导入 cypress 插件 index.ts 的函数?

How to correctly export and import functions for cypress plugin index.ts?

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

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

但我不能让它为我的情况工作。

这是我的 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 中遇到这个错误:

从post可以看出TS是混合JS的。例子是JS,你用的是TS,所以没有module.exports.

尝试纯 JS 版本,然后将其转换为 TS。

看来问题出在您的 module.exports 和导入上。

试试这个,

// document.ts

export async function uploadDocument(fileName: string) { ... }
// module.exports = { uploadDocument }
// plugins/index.ts

import { uploadDocument } =  from './documents'

如果您查看 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
  //
  //
}