skip to Main Content

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}}`)
}

2

Answers


  1. To make the property you’re accessing from the JSON file dynamic, you can use bracket notation in JavaScript. This lets you access an object’s properties based on a variable rather than hard-coding the property key. Here’s how you can update your function:

    async answerMyDetails(answerSet){
        const testDataFile = './myJsonFile.json';
        let data = await fs.readFile(testDataFile);
        let testData = await JSON.parse(data);
    
        // Use bracket notation to dynamically access the property
        await this.page.locator(`div:has(> label:has-text("Some Text")) input`).fill(`${testData.myDetailsPageQuestions.vehicleReg.answer[answerSet]}`);}
    

    And here is the explanation on what’s going on here:

    By using answer[answerSet], you can pass the key you want (fullUkLicence_carInsurance, for example) as a parameter when you call the function. This avoids hard-coding the property name and makes it more flexible.

    So, when you call answerMyDetails(‘fullUkLicence_carInsurance’), it will dynamically fill the input field with the corresponding value from your JSON file.

    Hope this helps! Let me know if you have any questions.

    Login or Signup to reply.
  2. 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}`])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search