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:
- 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"),
});
- 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>
- 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.
Learn more at www.vitest-preview.com