skip to Main Content

I have a disabled input field, and I want to enable it using Playwright.

 <form action="/action_page.php">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname" disabled>
  <input type="submit" value="Submit">
</form> 

I want to check if a low permission level user enables it through dev-tools, the submit form would block/fail.

Please note that I’m unable to execute direct API calls to test that.

2

Answers


  1. Chosen as BEST ANSWER

    I've found a solution using the evaluate method.
    The evaluate method allows you to execute JavaScript code in the context of the browser.

    In this case I'm using it to remove the disabled attribute of the input field:

    const inputSelector = "#fname";
    await page.locator(inputSelector).evaluate((el) => el.removeAttribute("disabled"));
    

  2. You can use the following approach which follows PW best practices by auto-waiting and locating by user-visible aria role and name.

    import {expect, test} from "@playwright/test"; // ^1.42.1
    
    const html = `<!DOCTYPE html><html><body>
    <form action="/action_page.php">
      <label for="fname">First name:</label>
      <input type="text" id="fname" name="fname" disabled>
      <input type="submit" value="Submit">
    </form>
    </body></html>`;
    
    test("input can be disabled with JS", async ({page}) => {
      await page.setContent(html);
      const input = page.getByRole("textbox", {name: "First name:"});
      await expect(input).toHaveAttribute("disabled");
      await input.evaluate(el => el.removeAttribute("disabled"));
      await expect(input).not.toHaveAttribute("disabled");
    });
    

    However, .evaluate is a slight antipattern and this is a rather strange thing to want to test, since JS console "interaction" isn’t a typical user behavior. A savvy user should be able to send the form request by other means than input elements if they really want to. So this could be an XY problem. But if that’s the specification you’re being forced to test by the powers that be and can’t push back, such it is.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search