在 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);
},
})
},
确切的代码取决于您如何设置nx工作区,但关键是任务中的
__dirname
是绝对路径,而浏览器中的__dirname
是相对路径(由于沙箱安全性)。
如果添加任务,可以将相对路径转换为绝对路径
setupNodeEvents(on, config) {
on('task', {
absolutePath(relativePath) {
const absolutePath = path.join(__dirname, '../../', relativePath)
return absolutePath;
},
})
注释
\\
分隔符,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')
})
因此您的测试可以传递相对于 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);
},
})
}