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

Ways to fix the TypeError that occurs when attempting to convert undefined or null to an object by using Function.keys

I am attempting to conceal the field. When the user clicks on glyphicon-eye-open, I will display glyphicon-eye-close and set the condition to true. If the condition is true, then I push that value into an array. Here is the function I am using, I have two ...

Javascript animation functioning for a singular item within a list

As I continue practicing my skills in Javascript and HTML, I stumbled upon this intriguing list known as "item/adapter", similar to what we refer to as adapters in Android. While the process of adding them programmatically to my div is working smoothly, I& ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Replacing text using regex results in whitespace

How can I eliminate text and spaces? For instance: http://www.exampleweb.com/myprogram.rar http://www.examplebackup.com/mybackups.rar http://www.exampleweb.com/myprogram1.rar I have used something similar to remove the second line: http://www.exampleba ...

Iterate through the object received from the node promise and pass it to the subsequent .then method

After grappling with this issue for what feels like an eternity, I find myself immersed in learning about Node.js and trying to grasp the concept of promises. My current challenge involves retrieving data from the Spotify API, starting with fetching my ow ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Should we consider using extra url query parameters as a legitimate method to avoid caching or enforce the updating of css/js files?

Is it acceptable to include extra URL query parameters in order to avoid caching or enforce the updating of CSS/JS files? /style.css?v=1 Or would it be preferable to rename the file/directory instead? /style.1.css I've heard that this could potent ...

Retrieve the elements by their IDs in an svg where the ID equals '@data[]'

As I load data from SQL in a while loop to create my SVG, each record has its own ID. However, when attempting to retrieve the ID using getelementbyId, it consistently returns null values. Below is the code snippet: #!/usr/bin/perl use DBI; use CGI::Carp ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

What are the steps to integrating AngularJS with ES6?

Combining AngularJS and ES6 with webpack as the building tool is my current project. I'm seeking advice on how to successfully integrate them - can anyone offer any insights or guidance? ...

Conceal the div element five seconds after the registration process is completed

Is it possible to automatically hide a div 5 seconds after a user registers? Using the timestamp in PHP for the user's registration, there may be a way to achieve this with jQuery, but it's not certain. I found a script online that successfully ...

To customize or not to customize?

Lately, there has been a growing trend of people incorporating custom attributes into their HTML tags to add extra data for use in JavaScript code. I'm curious to hear thoughts on the practice of using custom attributes and what alternatives are avai ...

What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element? Here is the code I am using: $(".menu_list_item").css({ width: width + "%" }); Unfortunately, this doesn't appear to be functioning correctly. If anyo ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

What is the best way to assign the result of a promise to a variable?

My code includes an async function that retrieves a value async fetchUserName(environment: string, itemName: string, authToken: string): Promise<any> { let result = await this.obtainDeviceName(environment, itemName, authToken); return ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Utilize jQueryUI sortable to serialize a list item within an unordered list

I'm looking to learn how to generate a JSON or serialize from a ul element with nested list items. Here's an example: <ul class="menu send ui-sortable"> <li id="pageid_1" class="ui-sortable-handle">Inscription <ul class="menu ...