I have seen various posts about testing APIs using a custom built nodejs script and not being able to get screenshots. Following the Synthetics and Playwright documentation this is the sort of thing I would like to do:
import { journey, step, expect, request } from '@elastic/synthetics';
import jwt from "jsonwebtoken";
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs');
async function createTextImage(text, filename) {
const canvas = createCanvas(800, 600);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#FFFFFF'; // White background
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = '70px Impact';
ctx.fillStyle = '#000000'; // Black text
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const x = canvas.width / 2;
const y = canvas.height / 2;
ctx.fillText(text, x, y);
const buffer = canvas.toBuffer('image/png');
fs.writeFileSync(filename, buffer);
}
journey('API Testing', ({ page, context }) => {
step('make an API request', async () => {
const api = await playwright.request.newContext({
baseURL: 'https://api.github.com',
extraHTTPHeaders: {
'Authorization': `token ${process.env.API_TOKEN}`
},
});
const response = await api.get(params.url);
await expect(response.status()).toBe(200);
const body = await response.json();
await expect(body).toMatchObject({"current_user_url": "https://api.github.com/user"});
const textToRender = JSON.stringify(jsonData, null, 2);
// Create a PNG image
await createTextImage(textToRender, "screenshot.png");
// Import the PNG as a screenshot
await page.screenshot({ path: 'screenshot.png' });
});
});
This way I can use expect(body) to check for successful responses and specific items in the json response, and then generate a custom screenshot of the output into a buffer or png and then attach it to the step as the screenshot?
Is there any way to do this?