I would like to compile a list and push them into a json array in Cypress.
This is what the json out put is supposed to look like:
[
{
"role": "Administrator",
"scenarios": [
"clients_a",
"clients_d",
"clients_f",
....
]
}
]
This is my code so far:
const permission_list = require('../../fixtures/permissions/permissions_admin.json')
const test_plan = 'cypress/fixtures/permissions/test_plan_admin.json'
const role = 'Administrator'
describe('Test plan creator for Administrator', () => {
it('create a test plan', () => {
//prepare the json array
cy.writeFile(test_plan, [{role: role,scenarios: []}])
cy.get(permission_list[0].granted_permissions).then((list) => {
if (Cypress.$.inArray('clients', list) != -1) {
cy.readFile(test_plan).then((scenarios) => {
scenarios.push('clients_a') // this is where I make a mistake I suppose
// write the merged list
cy.writeFile(test_plan, scenarios)
})
}
///added to handle case "clients" was not found in Array
else {
}
})
})
})
And this is the output of my code:
[
{
"role": "Administrator",
"scenarios": []
},
"clients_a" <-- should be inside the list behind "scenarios"
]
So it's close but no cigar. How can I push the value "clients_a"
into the list of "scenarios"
?
The approach I would take is do everything in memory and only write the finished list once at the end.
There would be a slight speed up doing that, but main advantage is you don't need to worry about appending.
const permission_list = require('../../fixtures/permissions/permissions_admin.json')
const test-plan-file-path = 'cypress/fixtures/permissions/test_plan_admin.json'
const role = 'Administrator'
describe('Test plan creator for Administrator', () => {
it('create a test plan', () => {
//prepare the json array
const scenarios = []
cy.get(permission_list[0].granted_permissions).then((list) => {
if (Cypress.$.inArray('clients', list) != -1) {
scenarios.push('clients_a')
}
})
// write the result
const plan = [{ role, scenarios}]
cy.writeFile(test-plan-file-path, plan)
})
})
There's something else strange here, it looks like you push multiple items in a loop, but there is no loop here. Would need to see more of the app to suggest how to fix that.