Full article on Medium: https://matteolobello.medium.com/ui-testing-typescript-react-apps-with-puppeteer-and-jest-a48684f5d8dc
Last active
November 3, 2023 07:48
-
-
Save matteolobello/a6a9d29bccca4438b0b3b80730da5576 to your computer and use it in GitHub Desktop.
UI Testing TypeScript React apps with Puppeteer and Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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?.()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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