Site settings
Change the appearance of the site to suit your preferences
How to Write Tests
Testing is a crucial part of development. This guide will walk you through writing tests for Spor components to ensure quality, accessibility, and reliability.
🔍 How We Test
We use Vitest, Testing Library, and Axe to test our code in Spor. This combination makes it easy to write tests that also check for universal accessibility compliance. If you're new to these tools, it's worth taking a quick look at their documentation:
- VitestEkstern lenke
- Testing LibraryEkstern lenke
- Axe for AccessibilityEkstern lenke
📝 Writing Your First Test
To get started, find a component you want to test (e.g., Button.tsx), and create a new test file in the same folder: Button.test.tsx. You can start with this simple test setup:
import { act, render } from "@testing-library/react";import React from "react";import { axe } from "vitest-axe";describe("<Button />", () => {it("", async () => {// TODO: Write the test!});});
🖱️ Example: Testing a Button Component
A simple test for a button might look like this:
import { vi } from "vitest";import { act, render } from "@testing-library/react";import React from "react";import { axe } from "vitest-axe";import { Button } from "@vygruppen/spor-react";describe("<Button />", () => {it("works like a button", async () => {const handleClick = vi.fn();const { getByRole } = render(<Button variant="primary" onClick={handleClick}>Click me</Button>);getByRole("button").click();expect(handleClick).toHaveBeenCalled();});});
♿ Testing for Accessibility
Axe helps ensure your code meets accessibility standards. Here’s how you can test it:
it("is accessible", async () => {const { container } = render(<Button variant="primary">Click me</Button>);expect(await axe(container)).toHaveNoViolations();});
🔹 It’s a good idea to run this multiple times in different component states.
🚀 Test Smarter, Not Harder
🔹 Accessibility testing is tricky—even with Axe, only about 20% of accessibility bugs get caught automatically. Always test with a screen reader and keyboard navigation.
🔹 You don’t need 100% test coverage. Full test coverage can make refactoring difficult. Instead, write a few broad tests that cover most critical user flows efficiently.
🔧 Adding Tests to a Package That Doesn't Have Them
Not all Spor packages currently support testing. If you need to add test support to a package, follow these steps:
1. Add the required dependencies to package.json:
"devDependencies": {"@testing-library/react": "^latest","vitest": "^latest","vitest-axe": "^latest"}
2. Create a __tests__ directory inside the package.
3. Write a test file (e.g., ComponentName.test.tsx).
4. Run tests using:
npm test
By following these guidelines, you’ll help ensure that Spor components remain reliable, accessible, and easy to maintain! 🚀