Skip to main content

Customize HTML in Vitest

· 2 min read
Hung Viet Nguyen

In some scenarios, you may want to customize the HTML in Vitest 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 environmentOptions

Update to vitest.config.js or vitest.config.ts:

export default {
test: {
environment: 'jsdom', // or 'happy-dom'
environmentOptions: {
jsdom: {
html: '<!DOCTYPE html><div id="root"></div></html>',
},
},
},
};

Use container option to specify container of your test:

root.id = "root";
render(<App />, {
container: document.getElementById("root"),
});
  1. Update HTML at runtime

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

// App.test.tsx
import { render } from '@testing-library/react';
import { test, expect } from 'vitest';
import App from './App';

const root = document.createElement("div");
root.id = "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):

<body>
<div id="root">
<!-- Your app's HTML -->
</div>
</body>
  1. Specify environment for specific test files

You can also set the environment and its options for specific test files using the @vitest-environment comment at the top of your test file:

// @vitest-environment jsdom
import { render } from '@testing-library/react';
import { test, expect } from 'vitest';
import App from './App';

test("should work correctly", () => {
const root = document.createElement("div");
root.id = "root";
render(<App />, {
container: document.body.appendChild(root),
});
});

Also, you can use Vitest Preview to preview a test directly in a browser.

Vitest Preview Demo

Learn more at www.vitest-preview.com