I’m trying to get the HTTP response status after a user signs up on my website. I’m using Puppeteer but I’m having trouble capturing the status code. Here’s what I’ve tried:
it('checks for 400 status when email is already used', async () => {
await page.goto('http://mysite.com/signup')
await page.waitForSelector('#name')
await page.type('#name', 'Han Solo')
await page.type('#email', '[email protected]')
await page.type('#password', 'ChewieIsMyBFF')
await page.click('button[type="submit"]')
const result = await page.on('response', res => res)
console.log('Status:', result.status)
// expect(result.status).toBe(400)
})
I’ve looked at the docs and tried different approaches, but I keep getting the whole page object instead of just the status. Any ideas on how to fix this? Thanks!
hey mate, try using the response event listener like this:
page.on('response', response => {
if (response.url().includes('/signup')) {
console.log('Status:', response.status());
}
});
this should capture the status code for the signup request. hope it helps!
Have you considered using the page.setRequestInterception(true) method? This can be quite effective for capturing HTTP responses. Here’s an approach that might work:
await page.setRequestInterception(true);
page.on('request', request => {
request.continue();
});
page.on('response', response => {
if (response.url().includes('/signup')) {
console.log('Status:', response.status());
}
});
await page.goto('http://mysite.com/signup');
// Perform your form submission here
This method intercepts all requests, allowing you to monitor responses more closely. It’s particularly useful when you need to track specific API calls or form submissions. Just remember to call request.continue() to prevent the page from hanging.
I’ve encountered similar issues with Puppeteer before. Here’s what worked for me:
Instead of using page.on('response'), try wrapping your form submission in a Promise.all() with page.waitForResponse(). This way, you can capture the specific response you’re interested in:
const [response] = await Promise.all([
page.waitForResponse(res => res.url().includes('/signup')),
page.click('button[type="submit"]')
]);
const status = response.status();
console.log('Status:', status);
expect(status).toBe(400);
This approach allows you to target the exact response you’re looking for and extract its status code reliably. It’s been a game-changer for my Puppeteer tests, especially when dealing with complex web applications.