如何将长时间运行的剧作家测试的进度发送到前端

问题描述 投票:0回答:1

我在节点后端定义了一条测试进度路由作为 SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events),

我正在前端初始化 url。

以下是服务器路由文件中的代码

let clients: Array<any> = [];

router.get('/progress', (req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
    });

    const data = `data: ${JSON.stringify('Starting the test')}\n\n`;

    res.write(data);

    const clientId = Date.now();

    const newClient = {
      id: clientId,
      res,
    };
    clients.push(newClient);
    req.on('close', () => {
      console.log(`${clientId} Connection closed`);
      clients = clients.filter((client) => client.id !== clientId);
    });
  });

我在前端有一个按钮,单击该按钮将在节点后端运行剧作家测试。

由于这是一个长时间运行的剧作家测试(循环遍历 csv 并检查),我想在中间将进度发送到前端。

我尝试将下面所示的 sendEventsToAll 函数(在服务器路由文件中定义)导入到测试中并调用它,但它不起作用,

export function sendEventsToAll(data: any) {
  console.log('SSE ' + data);
  clients.forEach((client) => client.res.write(`data: ${JSON.stringify(data)}\n\n`));
}

解决这个问题的最佳方法是什么,还有其他更好的方法吗?

谢谢。

typescript playwright playwright-typescript
1个回答
0
投票

所以看起来您已经设置了路由

/progress
将 SSE 发送给客户端。您可以创建一个单独的函数来发送进度更新,而不是直接调用
sendEventsToAll
函数:

    let clients: Array<any> = [];

router.get('/progress', (req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
    });

    const data = `data: ${JSON.stringify('Starting the test')}\n\n`;

    res.write(data);

    const clientId = Date.now();

    const newClient = {
      id: clientId,
      res,
    };
    clients.push(newClient);
    req.on('close', () => {
      console.log(`${clientId} Connection closed`);
      clients = clients.filter((client) => client.id !== clientId);
    });

    // Expose a function to send progress updates
    res.sendEventsToAll = (data: any) => {
        console.log('SSE ' + data);
        clients.forEach((client) => client.res.write(`data: ${JSON.stringify(data)}\n\n`));
    };
});

// Function to send progress updates
export function sendProgressUpdate(data: any) {
    // Invoke the function added to the response object
    res.sendEventsToAll(data);
}

现在从您的剧作家测试中导入

sendProgressUpdate
并使用它发送更新:

import { sendProgressUpdate } from './yourRouteFile'; // Replace 'yourRouteFile' with the path to your route file

// Inside your Playwright test loop or wherever you want to send updates
// Assuming you have some variable 'progressData' containing the progress information
sendProgressUpdate(progressData);
© www.soinside.com 2019 - 2024. All rights reserved.