Sitemap
Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Follow publication

Testing your React App with Puppeteer and Jest

Rajat S
12 min readMay 7, 2018

--

Build in AI speed — Compose enterprise-grade applications, features, and components
Build in AI speed — Compose enterprise-grade applications, features, and components

Project Setup

git clone https://github.com/rajatgeekyants/test.git
yarn install
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"debug": "NODE_ENV=debug npm test",
"eject": "react-scripts eject",
}

Testing HTML Content with Puppeteer

yarn debug
<nav className='navbar'>
<ul>
<li className="nav-li"><a href="#">Batman</a></li>
<li className="nav-li"><a href="#">Supermman</a></li>
<li className="nav-li"><a href="#">Aquaman</a></li>
<li className="nav-li"><a href="#">Wonder Woman</a></li>
</ul>
let browser
let page
beforeAll(async () => {
browser = await puppeteer.launch(isDebugging())
page = await browser.newPage()
await page.goto(‘http://localhost:3000/')
page.setViewport({ width: 500, height: 2400 })
})
afterAll(() => {     
if (isDebugging()) {
browser.close()
}
})
test('nav loads correctly', async () => {
const navbar = await page.$eval('.navbar', el => el ? true : false)
const listItems = await page.$$('.nav-li')
expect(navbar).toBe(true)
expect(listItems.length).toBe(4)
});

Replicating User Activity

state = { complete: false }handleSubmit = e => {
e.preventDefault()
this.setState({ complete: true })
}
{ this.state.complete ? 
<SuccessMessage/>
:
<Login submit={this.handleSubmit} />
}
const faker = require('faker')const user = {
email: faker.internet.email(),
password: 'test',
firstName: faker.name.firstName(),
lastName: faker.name.lastName()
}
test('login form works correctly', async () => {
await page.click('[data-testid="firstName"]')
await page.type('[data-testid="lastName"]', user.firstName)

await page.click('[data-testid="firstName"]')
await page.type('[data-testid="lastName"]', user.lastName)

await page.click('[data-testid="email"]')
await page.type('[data-testid="email"]', user.email)
await page.click('[data-testid="password"]')
await page.type('[data-testid="password"]', user.password)
await page.click('[data.testid="submit"]')
await page.waitForSelector('[data-testid="success"]')
}, 1600)

Set Cookies from within the Tests

describe('login form', () => {
// insert the login form inside it
})
test('sets firstName cookie', async () => {
const cookies = await Page.cookies()
const firstNameCookie = cookies.find(c => c.name === 'firstName' && c.value === user.firstName)
expect(firstNameCookie).not.toBeUndefined()
})
state = {
complete: false,
firstName: '',
}
document.cookie = `firstName=${this.state.firstname}`
handleInput = e => {
this.setState({firstName: e.currentTarget.value})
}
<Login submit={this.handleSubmit} input={this.handleInput} />
handleSubmit = e => {
e.preventDefault()
if (document.cookie.includes('JWT')){
this.setState({ complete: true })
}
document.cookie = `firstName=${this.state.firstName}`
}
await page.setCookie({ name: 'JWT', value: 'kdkdkddf' })

Screenshots with Puppeteer

if (listItems.length !== 3) 
await page.screenshot({path: 'screenshot.png'});
expect(listItems.length).toBe(3);

Handle Page Requests in Tests

async componentDidMount() {
const data = await fetch('https://pokeapi.co/api/v2/pokedex/1/').then(res => res.json())
this.setState({pokemon: data})
}
<h3 data-testid="pokemon">
{this.state.pokemon.next ? 'Received Pokemon data!' : 'Something went wrong'}
</h3>
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url.includes('pokeapi')) {
interceptedRequest.abort();
} else {
interceptedRequest.continue();
}
});
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url.include('pokeapi')) {
interceptedRequest.abort();
} else {
interceptedRequest.continue();
}
});

--

--

Bits and Pieces
Bits and Pieces

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Responses (16)

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy