In the node backend, I have defined a route for test progress using SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
The URL initialization is happening on the frontend.
Below is the code snippet from the server route file:
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);
});
});
On the frontend side, there is a button that when clicked triggers a playwright test in the node backend.
Considering this test can be long-running (looping through a csv and checking), I want to send the progress updates to the frontend periodically.
I attempted to import and use the sendEventsToAll function (defined in the server route file) as shown below within the test script, but it seems to not work:
export function sendEventsToAll(data: any) {
console.log('SSE ' + data);
clients.forEach((client) => client.res.write(`data: ${JSON.stringify(data)}\n\n`));
}
Could you suggest the best approach to address this issue or if there's a better alternative solution? Your insights are appreciated.
Thank you.