I am trying to set a variable that will contain a part of a URL (a UUID) which I would then like to use in separate test suites. This snippet of the URL will be different every time so I cannot set it in the cypress.json within the "env" options. Code is as follows -
cy.location().then(fullUrl => {
let pathName = fullUrl.pathname
let arr = pathName.split('/');
const teamsTeamID = arr[4]
cy.log(teamsTeamID)
})
I would then like to use teamsTeamID in a separate teardown test to delete the team at the end of every test run but the team ID will be different every time I run the test - Is there a way to do this?
You can use fixtures and then use readFile and writeFile to achieve this.
First create a json inside your fixtures folder urldata.json
{
"uuid": "17289-YEHBE-893"
}
Then in your test you can write:
var teamsTeamID;
cy.location().then(fullUrl => {
let pathName = fullUrl.pathname
let arr = pathName.split('/');
teamsTeamID = arr[4]
cy.log(teamsTeamID)
})
cy.readFile("cypress/fixtures/urldata.json", (err, data) => {
if (err) {
return console.error(err);
};
}).then((data) => {
data.uuid = teamsTeamID
cy.writeFile("cypress/fixtures/urldata.json", JSON.stringify(data))
})
So now every time you run the test, you will have different values of UUID in your json file. Next you can use the value from fixtures directly into other tests:
describe('Some page', () => {
beforeEach(function () {
// "this" points at the test context object
cy.fixture('urldata.json').then((urldata) => {
// "this" is still the test context object
this.urldata = urldata
})
})
// the test callback is in "function () { ... }" form
it('check uuid', function () {
// this.urldata exists
expect(this.urldata.uuid).to.equal('some uuid')
})
})
Point to be noted:
If you store and access the fixture data using this test context object, make sure to use function () { ... } callbacks. Otherwise the test engine will NOT have this pointing at the test context.