'How to interact with a JSON configuration file in Cypress
My frontend depends of a json configuration file that holds various parameters that can modify the content of the page.
When the test starts, my file has a specific content. I would like to find a way to write this file but only for the current test so no state is left for the next test.
This is my current solution, but problem is that if tests fail, the original version of the file is not reset. What could be another approach ?
it('should work a specific way with the given configuration', () => {
cy.readFile('my-app/parameters.json').then(
(originalFile) => {
// Modify the json file however I'd like
cy.writeFile('my-app/parameters.json', someConfiguration);
// Test details
cy.writeFile('my-app/parameters.json', originalFile);
}
);
});
Solution 1:[1]
There's nothing really wrong with what you're doing (it's like resetting a database).
But perhaps use a different name for the original?
it('should work a specific way with the given configuration', () => {
cy.readFile('defaultParameters.json').then(
(originalFile) => {
// Modify the json file however I'd like
cy.writeFile('parameters.json', someConfiguration);
// Test details
}
);
});
Keep in mind when the test fails mid way you might not write the original back.
Move cy.readFile('defaultParameters.json') to cy.fixture('defaultParameters.json') since Cypress caches the fixture read.
See fixture - Loaded just once
Please keep in mind that fixture files are assumed to be unchanged during the test, and thus the Test Runner loads them just once. Even if you overwrite the fixture file itself, the already loaded fixture data remains the same.
If you wish to dynamically change the contents of a file during your tests, consider cy.readFile() instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
