Skip to content

Instantly share code, notes, and snippets.

@matteolobello
Last active November 3, 2023 07:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matteolobello/a6a9d29bccca4438b0b3b80730da5576 to your computer and use it in GitHub Desktop.
Save matteolobello/a6a9d29bccca4438b0b3b80730da5576 to your computer and use it in GitHub Desktop.
UI Testing TypeScript React apps with Puppeteer and Jest
import puppeteer from "puppeteer"
let browser: puppeteer.Browser | undefined
let page: puppeteer.Page | undefined
const sleep = async (ms: number) =>
await new Promise((res) => setTimeout(res, ms))
beforeAll(async () => {
browser = await puppeteer.launch({
headless: false
})
page = await browser.newPage()
await page.goto("http://localhost:3000")
}, 30_000)
test("Increments the counter correctly", async () => {
await sleep(1_000)
if (!page) {
throw new Error("Error while loading Puppeteer page")
}
const btn = await page.$("button")
if (!btn) {
throw new Error("Can't find the increase counter button")
}
const CLICK_TIMES = 10
for (let i = 0; i < CLICK_TIMES; i++) {
btn.click()
await sleep(250)
}
const counterSpan = await page.$("#counter")
if (!counterSpan) {
throw new Error("Can't find the counter span")
}
const counterSpanValue = await counterSpan.evaluate((el) => el.innerText)
expect(counterSpanValue).toBe(CLICK_TIMES.toString())
}, 30_000)
afterAll(async () => await browser?.close?.())
import { useState } from "react"
export default function App() {
const [counter, setCounter] = useState<number>(0)
return (
<div>
<h1>Counter</h1>
<span id="counter">{counter}</span>
<button onClick={() => setCounter(counter + 1)}>+1</button>
</div>
)
}
export default {
roots: ["<rootDir>/src"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment