Reputation: 99
For Cypress tests I am setting up an email adress in a js file. Then I would like to use this variable in another file. With import/export it runs the entire script from the previous file, I only need the variable
Upvotes: 1
Views: 1224
Reputation: 99
Possible solution using Fixtures:
support/commands.js:
Cypress.Commands.add('generateFixtureEmail', () => {
cy.writeFile('cypress/fixtures/email.json', {
'hits':Cypress._.times(1, () => {
let randomNumber= Math.floor(Math.random() * 1001);
const email ='random+'+randomNumber+'@mail.com';
return {
'Email': email
}
})
})
a json file is made: fixtures/email.json
"hits": [
{
"Email": "[email protected]"
}
]
support/index.d.ts:
declare namespace Cypress {
interface Chainable<Subject = string> {
generateFixtureEmail(): Chainable<Element>;
}
integration/test-scripts/test.js:
describe('Test', function()
{
before(() => {
cy.generateFixtureEmail()
cy.fixture('email').then(function (data) {
this.data = data;
})
})
it('testcase 1', function () { cy.loginWithEmail(this.data.hits[0].Email)
note: do not commit the generated json file
Upvotes: 0
Reputation: 31924
You can move your email value to /cypress/support/index.js
and import into both tests.
Or define a custom command in /cypress/support/commands.js
and avoid having to import it.
// cypress/support/commands.js
Cypress.Commands.add('getEmail', () => '[email protected]')
// all tests
cy.getEmail().then(email => {
...
})
Unfortunately that makes a simple variable asynchronous and you have to access it with .then()
.
Environment variables for static data
If the data is static, you can define it as an environment variable,
In Cypress V9
// cypress.json
{
...
"env": {
"email": "[email protected]",
}
}
In Cypress V10
// cypress.config.js
const { defineConfig } = require('cypress')
module.exports = defineConfig({
projectId: '128076ed-9868-4e98-9cef-98dd8b705d75',
env: {
email: '[email protected]',
}
})
// all tests
const email = Cypress.env('email')
Actually, in Cypress v10 the config is now a javascript file so you should be able to set email
via a function
// cypress.config.js
const { defineConfig } = require('cypress')
module.exports = defineConfig({
projectId: '128076ed-9868-4e98-9cef-98dd8b705d75',
env: {
getEmail: () => {
return '[email protected]';
},
}
})
// all tests
const email = Cypress.env('getEmail')() // invoke the function
Upvotes: 1
Reputation: 10545
You should be able to use a named export to avoid running the tests in the exporting file.
export const email = ...
import {email} from ...
Upvotes: 0