mynameismyname1010101
mynameismyname1010101

Reputation: 409

Cypress not recognizing my imported module from outside /cypress directory

I am trying to import a module from a file outside my /cypress directory into the /cypress/integration directory's test.spec.js file like so:

import { LAB_MODEL } from '../../models/search/lab-model';

But inside this imported module "LAB_MODEL" there are other files being imported using the "@@" at the start of the file imports like

import ExperimentDetails from "@@/components/experiment/ExperimentDetails";

and I think this is why Cypress isn't working and giving me this error:

Error: Webpack Compilation Error
./models/search/lab-model.js
Module not found: Error: Can't resolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
resolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
  Parsed request is a module
  using description file: /Users/hidden/package.json (relative path: ./models/search)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module

So I think this is the reason why my test won't run, but I have no idea how to make Cypress recognize "@@" imports and can't find any documentation/stackoverflow answers, any help is appreciated, thanks!

Upvotes: 3

Views: 2647

Answers (1)

user14783414
user14783414

Reputation:

@@/ looks like something that gets translated into a full path during the Nuxt build.
(ref The alias Property).

Cypress has a separate build that doesn't know about this Nuxt feature. You could try to replicate it with some webpack config via a preprocessor, but another way is to have your Nuxt app put a reference to lab_model on the window object

// somewhere in the Nuxt app
if (window.Cypress) {
  window.lab_model = LAB_MODEL;
}

then at the top of the test

const lab_model = cy.state('window').lab_model;

This has the benefit of giving you the exact same instance of lab_model, in case you wanted to stub something.


In a starter Nuxt app, I added the code window.lab_model = LAB_MODEL in /pages/index.vue, but you can add it in any component that imports it, right after the import statement.

In the spec add a .should() to test the property exists, to allow the app time to settle.

it('gets labModel from the Nuxt app', () => {

  cy.visit('http://localhost:3000/')

  cy.window()
    .should('have.property', 'lab_model')  // retries until property appears
    .then(labModel => {

      console.log(labModel)

      // test with labModel here
    })
})

Upvotes: 1

Related Questions