I have a JSON file that I'm reading data from for a Playwright test as below:
async answerMyDetails(){
const testDataFile = './myJsonFile.json'
let data = await fs.readFile(testDataFile)
let testData = await JSON.parse(data)
await this.page.locator(`div:has(> label:has-text("Some Text")) input`).fill(`${testData.myDetailsPageQuestions.vehicleReg.answer_fullUkLicence_carInsurance}`)
}
I'd like to change this so that the _fullUkLicence_carInsurance part of the property that's being read from the JSON file is not hard coded and can be determined at the time the function is called, e.g. something like:
(answerSet == fullUkLicence_carInsurance)
async answerMyDetails(answerSet){
const testDataFile = './myJsonFile.json'
let data = await fs.readFile(testDataFile)
let testData = await JSON.parse(data)
await this.page.locator(`div:has(> label:has-text("Some Text")) input`).fill(`${testData.myDetailsPageQuestions.vehicleReg.answer_{answerSet}}`)
}
You can use bracket notation instead of dot notation to dynamically reference an object property name.
async answerMyDetails(answerSet){
const testDataFile = './myJsonFile.json'
let data = await fs.readFile(testDataFile)
let testData = await JSON.parse(data)
await this.page.locator(`div:has(> label:has-text("Some Text")) input`)
.fill(testData.myDetailsPageQuestions.vehicleReg[`answer_${answerSet}`])
}