获取Cypress测试文件中的项目根路径

问题描述 投票:0回答:1

在 Nx 工作区中,我正在使用 Cypress 测试一个应用程序

在嵌套在子文件夹中的规范文件之一中,如下所示

${PROJECT_FOLDER}/apps/${APP_NAME}/cypress/e2e/${SOME_FOLDER}/test.cy.ts

我想获取作为项目文件夹的子文件夹的文件夹(dist)的绝对路径

${PROJECT_FOLDER}/dist

如何获取 test.cy.ts 文件中

${PROJECT_FOLDER}/dist
的绝对路径?

我尝试使用

__dirname
,但它给了我
cypress/e2e/${SOME_FOLDER}/

我想通过 test.cy.ts 文件将此路径传递给 Cypress task,如下所示

//测试.cy.ts

 const filePath = 'path-to-file in ${PROJECT_FOLDER}/dist/some-file';
 cy.task('fileExists', filePath).should('equal', true);

cypress.config.ts
文件中的 Cypress 任务

setupNodeEvents(on, _config) {
  on('task', {
    fileExists(filePath: string) {
      return fs.existsSync(filePath);
    },
  })
},
node.js angular cypress nrwl-nx
1个回答
0
投票

确切的代码取决于您如何设置nx工作区,但关键是任务中的

__dirname
是绝对路径,而浏览器中的
__dirname
是相对路径(由于沙箱安全性)。

如果添加任务,可以将相对路径转换为绝对路径

  setupNodeEvents(on, config) {
    on('task', {
      absolutePath(relativePath) {
        const absolutePath = path.join(__dirname, '../../', relativePath)
        return absolutePath;
      },
    })

注释

  • windows 路径,使用
    \\
    分隔符,linux 路径使用
    /
    分隔符
  • 假设
    cypress.config.ts
    位于
    PROJECT_FOLDER/apps/APP_NAME
    中,否则调整
    ../../
    以适合其位置。
cy.task('absolutePath', '/dist/example.json')
  .then(absolutePath => {
    assert(absolutePath === `${PROJECT_FOLDER}\\dist\\example.json`, 'absolutePath is correct')
  })

enter image description here


因此您的测试可以传递相对于 PROJECT_FOLDER 的路径,并让任务构造绝对路径。

const relativeFilePath = '/dist/example.json';
cy.task('fileExists', relativeFilePath).should('equal', true)
setupNodeEvents(on, _config) {
  on('task', {
    fileExists(filePath) {
      const absoluteFilePath = path.join(__dirname, '../../', relativeFilePath)
      return fs.existsSync(absoluteFilePath);
    },
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.