node.jsangularcypressnrwl-nx

Get project root path in Cypress test file


In a Nx workspace I have an app that I am testing using Cypress

In one of the spec files nested within a subfolder as below

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

I want to get the absolute path to a folder (dist) that is a sub-folder of the project folder

${PROJECT_FOLDER}/dist

How can I get the absolute path to ${PROJECT_FOLDER}/dist within the test.cy.ts file?

I tried using __dirname but it gives me cypress/e2e/${SOME_FOLDER}/

I want to pass this path to a Cypress task from within the test.cy.ts file like below

// test.cy.ts

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

Cypress task in cypress.config.ts file

setupNodeEvents(on, _config) {
  on('task', {
    fileExists(filePath: string) {
      return fs.existsSync(filePath);
    },
  })
},

Solution

  • The exact code depends on how you have set up your nx workspace, but the key is __dirname inside the task is an absolute path, whereas __dirname in the browser is a relative path (due to sandboxing security).

    If you add a task you can convert the relative path to an absolute path

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

    Notes

    cy.task('absolutePath', '/dist/example.json')
      .then(absolutePath => {
        assert(absolutePath === `${PROJECT_FOLDER}\\dist\\example.json`, 'absolutePath is correct')
      })
    

    enter image description here


    So your test could pass a path relative to PROJECT_FOLDER, and have the task construct the absolute path.

    const relativePath = '/dist/example.json';
    cy.task('fileExists', relativePath).should('equal', true)
    
    setupNodeEvents(on, _config) {
      on('task', {
        fileExists(relativePath) {
          const absolutePath = path.join(__dirname, '../../', relativePath)
          return fs.existsSync(absolutePath);
        },
      })
    }