Skip to main content

Customize HTML in Jest

· One min read
Hung Viet Nguyen

In some scenarios, you may want to customize the HTML in Jest to align with your actual app's HTML structure. You can do it by one of the following options:

  1. Update the initial HTML by testEnvironmentOptions

Update to jest.config.js

testEnvironmentOptions: {
html: '<!DOCTYPE html><div id="root"></div></html>',

Use container option to specify container of your test = "root";
render(<App />, {
container: document.getElementById("root"),
  1. Update HTML at runtime

Use container of @testing-library/react's render function (Please refer to if you are using @testing-library/other-framework)

// App.test.tsx
const root = document.createElement("div"); = "root";

test("should work correctly", () => {
render(<App />, {
// Add container here 👇
container: document.body.appendChild(root),

You can assert your HTML by console.log(document.body.outerHTML)

<div id="root">
<!-- Your app's HTML -->

Or just see it directly in a browser using Jest Preview

Jest Preview Demo