Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright

Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete mode button is re-enabled.

How can I create a test scenario where I click on the refresh button and verify that the delete mode button is disabled before the mocked request completes?

I've attempted the following approach but the assertion consistently passes even with attempts to use .not to potentially fail it (resulting in false positives).

it('should disable delete button during refresh', async ({ page }) => {
  const deleteBtn = page.getByRole('button', {name: 'enter delete mode'}).first();
  page.on('request', () => { expect(deleteBtn).toBeDisabled() }) // false positive
  await page.getByText('REFRESH', { exact: true}).click();
});

Answer №1

One way to guarantee that you catch the button in the correct state of being disabled is by intercepting the network request and mocking its response. This ensures a specific window where the button's status can be observed accurately. Mocking also helps link the assertion within the callback to the main promise chain in the test case, preventing the test from concluding before the assertion is executed.

Below is a concise and verifiable example:

import {expect, test} from "@playwright/test"; // ^1.39.0

const html = `<!DOCTYPE html>
<html>
<body>
<button>enter delete mode</button>
<button>REFRESH</button>
<script>
const [deleteModeBtn, refreshBtn] = document.querySelectorAll("button");
refreshBtn.addEventListener("click", e => {
  deleteModeBtn.setAttribute("disabled", true);
  fetch("https://jsonplaceholder.typicode.com/users")
    .finally(() => {
      deleteModeBtn.removeAttribute("disabled");
    });
});
</script>
</body>
</html>`;

test("button is disabled during the request", async ({page}) => {
  await page.setContent(html);
  const btn = page.getByRole("button", {name: "enter delete mode"});
  await page.route("*/**/users", async route => {
    await expect(btn).toBeDisabled();
    await route.fulfill({});
  });
  await expect(btn).toBeEnabled();
  await page.getByText("REFRESH", {exact: true}).click();
  await expect(btn).toBeEnabled();
});

To confirm that this test successfully verifies the button's disabled state during the network request, simply comment out

btn.setAttribute("disabled", true)
or
btn.removeAttribute("disabled")
, which will result in the failure of the test.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript is unable to identify one of the JSON values

I am trying to extract the email field from a JSON file using JavaScript. Here is the snippet of code: "contacts": [ { "addedAt": 1332358711001, "vid": 1, "properties": { ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

NavigAuth - NativeScript Vue's Innovative Authentication-driven Navigation

After spending hours trying to figure this out, I need to ask for help. How can I create a simple Auth-based Navigation within my App? I have successfully set up a Firebase auth user inside my Vuex using an auth listener. Now, all I want is to display th ...

Tips for targeting an element for focus following a re-render in ReactJS

Within my web application, when a user hits the enter key, they are able to save the current record. A message confirming that the "record has been successfully saved" is then displayed. However, I have noticed that the blinking cursor in one of the input ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

Every time I hover, my jQuery code keeps repeating the hover effect

I am currently facing an issue that has me stumped on finding a solution. The problem arises when I hover over the .div multiple times, the animation just doesn't stop and keeps running continuously. What I aim for is to have the .hidden element fad ...

Ways to control the number of boxes that are checked

I am currently working on a script to restrict the number of checkboxes that can be checked, but I am encountering an issue where the script is disabling all checkboxes on the page. Is there a way to only disable a specific checkbox within a certain div? ...

When attempting to push `content[i]` into an array in AngularJS, it is flagged

In my JSON data, I have the following structure: var data = [{ id: 1, name: 'mobile', parentid: 0, limit:3 }, { id: 2, name: 'samsung', parentid: 1 }, { id: 3, name: 'moto', parenti ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...

Utilizing jQuery AJAX to efficiently handle branching based on the result received

I've successfully set up my first AJAX call with jQuery. The only thing left to do is to check the result from the PHP page for any database errors and display an error message if necessary. Here's the current Javascript code: <script type=" ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Error: An attempt to make changes to a database that does not permit mutations has resulted in an InvalidStateError

I am facing an issue while attempting to initiate a transaction within the then() function. An exception is thrown when I try to do so. Below is the code snippet in question: open.onsuccess = function (e1) { var dbase = e1.target.result; $.get("https://w ...

Guide to setting up a custom js file in Laravel admin template

Currently working with Laravel 5.8 and utilizing the laravel-admin Template for administrative purposes. There are times when I require custom JavaScript and CSS files specifically for certain admin controllers. How can I include these JS and CSS in lara ...