Testing with Vitest
Protect behaviour with fast tests that run in the same modern toolchain.
What you will be able to do
- Write describe, it and expect blocks
- Choose the right matcher
- Cover edge cases
Vitest runs tests in a Vite project with almost no configuration. Tests are small functions that assert what the code should do.
import { describe, expect, it } from "vitest";
import { slugify } from "./slugify.js";
describe("slugify", () => {
it("lowercases and joins words", () => {
expect(slugify("Learn JavaScript")).toBe("learn-javascript");
});
it("trims surrounding spaces", () => {
expect(slugify(" Hello World ")).toBe("hello-world");
});
it("handles an empty string", () => {
expect(slugify("")).toBe("");
});
});- Run the suite with npx vitest or an npm test script.
- toBe compares primitives; toEqual compares object contents.
- Test the empty case, the boundary and the happy path.
- One behaviour per test keeps failures readable.
Your turn
MediumTest a clamp function
Write three tests for clamp(value, min, max): below the range, inside the range and above the range.
JAVASCRIPT · starter
import { describe, expect, it } from "vitest";
import { clamp } from "./clamp.js";
describe("clamp", () => {
// your tests here
});Check your understanding before moving on.
Knowledge checkQuestion 1
Which matcher compares object contents?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.