Qunit - AI-Powered Test Generator for Moleculer.js
Qunit is an intelligent VS Code extension that automatically generates high-quality unit and integration tests for your Moleculer.js microservices using AI. Say goodbye to tedious test writing and hello to comprehensive test coverage!

✨ Features
🤖 AI-Powered Test Generation
- Smart Test Planning: AI analyzes your code and proposes test scenarios categorized by priority (Critical, Logical, Error, Edge cases)
- Interactive Scenario Selection: Review and select which test scenarios to generate
- Context-Aware: Automatically includes dependencies and helper functions in generated tests
- Deep Mocking: Generates proper mocks for databases, external services, and broker calls
🎯 Moleculer.js Optimized
- Service Action Detection: Automatically detects Moleculer service actions
- Broker Call Mocking: Properly mocks
broker.call() with callThrough() support
- Database Mocking: Generates Sinon stubs for PostgreSQL queries
- Schema Validation: Includes parameter validation tests
🔄 Intelligent Test Management
- Test Plan Review: Review AI-generated test scenarios before generation
- Custom Instructions: Add specific testing requirements
- Merge & Update: Smart merging when updating existing tests
- Auto-Validation: Automatically runs and fixes failing tests (configurable)
📊 Visual Feedback
- Sidebar Panel: View all detected service actions at a glance
- Test Status Indicators: See which actions have tests (passed/failed/pending)
- Test Details View: Review generated tests, execution results, and AI analysis
- Progress Tracking: Real-time progress during test generation
🔧 Customizable
- Test Command: Configure your test runner (
npm test, yarn test, etc.)
- Auto-Validation: Enable/disable automatic test validation
- Max Fix Attempts: Control how many times AI tries to fix failing tests
- Firebase Integration: Optional test history persistence
📸 Screenshots
View all detected Moleculer service actions with test status
Test Plan Review
Review and select AI-generated test scenarios
Test Details
View generated tests, execution results, and AI analysis
🚀 Getting Started
Prerequisites
- VS Code 1.85.0 or higher
- Node.js project with Moleculer.js
- Mocha and Sinon installed (
npm install --save-dev mocha sinon)
Installation
- Install the extension from VS Code Marketplace
- Open a Moleculer.js project
- Click the Qunit icon in the Activity Bar
- Sign in with your Google account (for test history sync)
Quick Start
- Open your Moleculer service file (e.g.,
src/services/user.service.ts)
- Click the Qunit icon in the sidebar
- Select an action from the Action List
- Click the beaker icon (🧪) to generate tests
- Review the test plan and select scenarios
- Wait for generation - tests will be created automatically!
📖 Usage Guide
Generating Tests
Step 1: Detect Actions
The extension automatically scans your workspace for Moleculer service files and detects all actions.
Step 2: Generate Test Plan
Click the Generate Tests button (🧪) next to any action. The AI will:
- Analyze the function code
- Identify dependencies
- Propose test scenarios
- Categorize by priority
Step 3: Select Scenarios
Review the proposed scenarios and select which ones to generate:
- ✅ [Critical] - Core functionality tests
- 🧠 [Logical] - Business logic flows
- ⚠️ [Error] - Error handling tests
- 🔍 [Edge] - Edge case tests
Step 4: Add Custom Instructions (Optional)
Provide specific testing requirements:
- Mock the database to return empty results
- Test with invalid user permissions
- Verify error messages match exactly
Step 5: Review Generated Tests
The extension will:
- Generate complete test files with imports and setup
- Create proper mocks for database and broker calls
- Include assertions based on your code logic
- Open the test file for review
Running Tests
Manual Execution
Click the Run Test button (▶️) next to any action to execute its tests.
Auto-Validation
Enable auto-validation in settings to automatically run and fix tests after generation:
{
"ai-test-generator.autoValidateTests": true,
"ai-test-generator.maxFixAttempts": 3
}
Analyzing Tests
Click Analyze Tests to get AI feedback on:
- Coverage: Estimated code coverage percentage
- Accuracy: How well tests verify business logic
- Suggestions: Specific improvements (edge cases, better assertions, etc.)
Repairing Failing Tests
If tests fail, click Repair Tests to:
- Analyze error messages
- Generate fixes automatically
- Re-run tests
- Repeat up to
maxFixAttempts times
⚙️ Configuration
Extension Settings
{
// Enable automatic test validation after generation
"ai-test-generator.autoValidateTests": true,
// Maximum attempts to fix failing tests
"ai-test-generator.maxFixAttempts": 3,
// Command to run tests
"ai-test-generator.testCommand": "npm test"
}
Firebase Setup (Optional)
To enable test history persistence:
- Create a Firebase project
- Enable Google Authentication
- Create a Firestore database
- Deploy the backend API (see
api/README.md)
- Configure the extension with your Firebase credentials
🎓 Examples
Generated Test Example
Source Code:
// src/services/user.service.ts
actions: {
getUser: {
params: {
userId: "number"
},
async handler(ctx) {
const user = await this.adapter.findById(ctx.params.userId);
if (!user) {
throw new Error("User not found");
}
return user;
}
}
}
Generated Test:
// test/services/user.service.spec.ts
import { ServiceBroker } from "moleculer";
import { Client } from "pg";
import Sinon from "sinon";
import { expect } from "chai";
import schema from "../../src/services/user.service.ts";
describe("Test 'user' service", () => {
let broker: ServiceBroker;
let dbStub: Sinon.SinonStub;
beforeEach(async () => {
broker = new ServiceBroker({ logger: false });
broker.createService(schema);
await broker.start();
dbStub = Sinon.stub(Client.prototype, "query");
});
afterEach(() => Sinon.restore());
describe("Action: getUser", () => {
it("should return user when found", async () => {
const mockUser = { id: 1, name: "John Doe" };
dbStub.withArgs(Sinon.match(/SELECT.*FROM users/), [1])
.resolves({ rows: [mockUser], rowCount: 1 });
const result = await broker.call("user.getUser", { userId: 1 });
expect(result).to.deep.equal(mockUser);
});
it("should throw error when user not found", async () => {
dbStub.withArgs(Sinon.match(/SELECT.*FROM users/), [999])
.resolves({ rows: [], rowCount: 0 });
await expect(
broker.call("user.getUser", { userId: 999 })
).to.be.rejectedWith("User not found");
});
});
});
🔍 How It Works
1. Code Analysis
The extension uses AST parsing to:
- Extract Moleculer service actions
- Identify dependencies and imports
- Analyze function logic and control flow
2. AI Test Planning
Google's Gemini AI analyzes your code to:
- Understand business logic
- Identify test scenarios
- Prioritize by importance
- Suggest edge cases
3. Test Generation
The AI generates tests using:
- Few-shot learning from example patterns
- Context-aware prompts with your code
- Strict rules for Moleculer best practices
- Deep mocking for external dependencies
4. Validation & Repair
If auto-validation is enabled:
- Tests are executed automatically
- Errors are analyzed by AI
- Fixes are generated and applied
- Process repeats until tests pass
🛠️ Troubleshooting
Tests Not Generating
- Check Firebase connection: Ensure backend API is running
- Verify file structure: Tests should be in
test/ directory
- Check console: Look for errors in VS Code Developer Tools
Tests Failing After Generation
- Enable auto-validation: Set
autoValidateTests: true
- Increase fix attempts: Set
maxFixAttempts: 5
- Manual review: Check generated mocks match your code
Extension Not Detecting Actions
- File naming: Ensure files end with
.service.ts
- Moleculer structure: Actions must be in
actions: {} object
- Reload window: Try
Developer: Reload Window
📝 Best Practices
For Better Test Generation
- Write clear function names - Helps AI understand intent
- Add JSDoc comments - Provides context for test scenarios
- Keep functions focused - Easier to test and generate for
- Use TypeScript - Better type inference for mocks
For Test Maintenance
- Review generated tests - Always verify logic before committing
- Add custom scenarios - Use custom instructions for specific cases
- Keep examples updated - Good tests improve future generations
- Use test history - Learn from past generations
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
📄 License
This extension is licensed under the MIT License. See LICENSE for details.
🙏 Acknowledgments
📧 Support
Made with ❤️ by Q4US