Table of Contents
Automated testing is essential for maintaining code quality and ensuring your application runs smoothly. Bun, a modern JavaScript runtime, supports testing frameworks like Vitest, making it easier to write and run tests efficiently. This tutorial guides you through setting up automated tests in Bun using Vitest, step by step.
Prerequisites
- Node.js and npm installed on your system
- Basic knowledge of JavaScript and command-line interface
- Installed Bun runtime (visit bun.sh for installation instructions)
Step 1: Initialize a New Bun Project
Open your terminal and create a new directory for your project. Navigate into it and initialize a Bun project:
mkdir bun-vitest-demo
cd bun-vitest-demo
bun init
Step 2: Install Vitest
Install Vitest as a development dependency using Bun:
bun add -d vitest
Step 3: Configure Testing Script
Open your package.json file and add a test script:
"scripts": { "test": "vitest" }
Step 4: Create a Test File
Create a directory named tests and add a test file:
mkdir tests
touch tests/example.test.js
Step 5: Write a Sample Test
Open tests/example.test.js and add a simple test:
import { describe, it, expect } from 'vitest';
describe('Sample Test', () => {
it('checks if true is true', () => {
expect(true).toBe(true);
});
});
Step 6: Run the Tests
Back in your terminal, execute the test command:
bun run test
Conclusion
You have successfully set up automated testing in Bun using Vitest. As your project grows, continue adding more tests to ensure your code remains reliable and maintainable.