I need help getting the HTTP response status code when testing a user registration form with Puppeteer. I’m having trouble with the proper way to set up response listeners.
Here’s what I’m working with:
describe('User registration test', () => {
it('should return 400 when username already exists', async () => {
await browser.goto(`${config.BASE_URL}/register`)
await browser.waitForSelector('input[name="fullname"]')
await browser.type('input[name="fullname"]', 'John Doe')
await browser.type('input[name="email"]', '[email protected]')
await browser.type('input[name="password"]', 'password123', {delay: 50})
await browser.click('button[type="submit"]', {delay: 500})
const responseData = await browser.on('response', res => res)
console.log('status code:', responseData.status())
// expect(responseData.status()).toBe(400)
})
})
I also tried using request interception but that doesn’t seem right for my use case:
await browser.setRequestInterception(true);
browser.on('request', req => {
req.respond({
status: 404,
contentType: 'text/plain',
body: 'Page not found'
});
});
The main issue is that I keep getting the browser object back instead of the actual response. How do I properly capture HTTP responses in Puppeteer?
UPDATE - SOLUTION FOUND:
Thanks to the community help, I figured out the correct approach. The key was setting up the listener before making the request and running assertions inside the callback:
it('should return 400 when username already exists', async () => {
await browser.goto(`${config.BASE_URL}/register`)
await browser.waitForSelector('input[name="fullname"]')
await browser.type('input[name="fullname"]', 'John Doe')
await browser.type('input[name="email"]', '[email protected]')
await browser.type('input[name="password"]', 'password123', {delay: 50})
await browser.on('response', responseData => {
if (responseData.request().method() === 'POST' && responseData.url().includes('/api/users')) {
expect(responseData.status()).toBe(400)
}
})
await browser.click('button[type="submit"]', {delay: 500})
})
afterAll(async () => {
await puppeteerBrowser.close()
})
Hope this helps others facing the same issue!