Rayrun
← Back to Discord Forum

waiting for specific websocket message

I have this working but was wondering if there is a better way to test this:

test("yielding", async ({ page }) => {
  let first_iteration;
  let fourth_iteration;
  let last_iteration;
  
  page.on("websocket", (ws) => {
    first_iteration = ws.waitForEvent("framereceived", {
      predicate: (event) => {
        return JSON.parse(event.payload as string).msg === "process_generating";
      }
    });
  
    fourth_iteration = ws.waitForEvent("framereceived", {
      predicate: (event) => {
        return JSON.parse(event.payload as string)?.output?.data?.[0] === "3";
      }
    });
    
    last_iteration = ws.waitForEvent("framereceived", {
      predicate: (event) => {
        return JSON.parse(event.payload as string).msg === "process_completed";
      }
    });
  });
  
  const start_button = await page.locator("button", {
    hasText: /Start Iterating/
  });
  const textbox = await page.getByLabel("Iterative Output");
  await start_button.click();
  
  await first_iteration;
  await expect(textbox).toHaveValue("0");
  await fourth_iteration;
  await expect(textbox).toHaveValue("3");
  await last_iteration;
  await expect(textbox).toHaveValue("8");
});

This thread is trying to answer question "Is there a better way to test websocket messages using the waitForEvent function, and how to resolve the type issue with the function?"

3 replies

I'm also having an issue with the type.

let first_iteration: WebSocket["waitForEvent"];

This doesn't work because of the overloads, is there a way to extract the correct overload?

I also know about the possible race condition here, i can resolve that later if this is the only way to do this. But this feels messy and weird.

Double checking the docs one thing that seems off, all your ws.waitforEvent() are missing an await. It seems odd to be registering the same event, Would think you'd want to register the framereceived once but then look and inspect the payload for the toy inside, then set flags respective for each even you received. Then simply test/poll you've matched your condition...?

while( payload1 === false && payload2===false && payload3 ===false) {

}

I'm awaiting them later on, i need to attach the listeners to make sure they get registered. I don't want to block until later, and I want to do that in my test function rather than in the listener callback. I also need to assert in between awaits to ensure the values are correctly updated.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].