Reputation: 375
I've started with cypress automation and I'm struggling with JSON files.
Anyone knows how may I read a JSON file, let's say, located in ../example/vehicle.json?
I know cypress is JavaScript, but I'm also having trouble when importing JQuery in cypress project.
Upvotes: 6
Views: 26542
Reputation: 1
You might find this useful with your question and to organize your project. Let's say you have your input files here:
fixtures
│
└───website
│ orders.json
│ ...
│
└───mobile
subCancel.json
...
You can create a support method that returns the name of the folder in which a given json file is:
getFolderForJson(jsonName) {
let value;
switch (jsonName) {
case 'subCancel':
value = 'mobile';
break;
case ... //add your custom cases
}
return value;
}
Put the json reading logic in a command to be reused in your tests:
Cypress.Commands.add('readJson', (jsonName) => {
cy.fixture(jsonName).then(json => {
return JSON.parse(JSON.stringify(json)
);
});
});
And then use your json file properties in your test actions/assertions:
let folder = new BasePage().getFolderForJson(jsonName);
cy.readJson(folder + '/' + jsonName + '.json').then((data) => {
cy.get('selector').type(data.shippingAddress); //use your own json files/properties
}
Upvotes: 0
Reputation: 496
Create a UserData.json
file in fixtures folder and define your values something like this:
{
"Name": "Ghulam Nabi",
"Password":"Admin123"
}
Now, in your Test File
cy.fixture(‘UserData.json’).then((user) => {
cy.get(‘#txtUsername’).type(user.Name)
cy.get(‘#txtPassword’).type(user.Password)
});
This is just an example. You can Do a lot of things through this method.
Courtesy: https://softans.com/get-user-data-from-json-file-in-cypress/
Upvotes: -2
Reputation: 41
Hey Cypress geek I have success to use it
cy.fixture(profile.json).then((user) => {
// Delay each keypress by 0.1 sec
cy.get('#username').type(user.email, { delay: 100 }).should('have.value', user.email)
cy.get('#password').type(user.password)
})
Upvotes: 3
Reputation: 51
As far as I know, this would be the "Cypress" way to access data stored in a json file.
ref: https://docs.cypress.io/api/commands/fixture.html#Accessing-Fixture-Data
cy.fixture('user').then((user) => {
var name = user.name
var pass = user.password
})
Where 'user' is /fixtures/user.json
{
"name": "username",
"password": "password1234"
}
Upvotes: 5
Reputation: 375
Juste in case this can help anyone, there is a nice way to do this with the following line:
cy.readFile('path/to/file.json/txt/yaml')
https://docs.cypress.io/api/commands/readfile.html
Upvotes: 0
Reputation: 36
I have never worked with Cypress, on checking out the documentation this is something that I think could help you out
cy.fixture(filePath)
cy.fixture(filePath, encoding)
cy.fixture(filePath, options)
cy.fixture(filePath, encoding, options)
Please check out https://docs.cypress.io/api/commands/fixture.html#Syntax
Upvotes: 2