Some checks failed
Deploy / deploy (push) Has been cancelled
Full-stack web application for Telegram management - Frontend: Vue 3 + Vben Admin - Backend: NestJS - Features: User management, group broadcast, statistics 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
6.3 KiB
6.3 KiB
Telegram Management System - Test Suite
This directory contains comprehensive unit and integration tests for the Telegram Management System backend.
Test Structure
test/
├── setup.js # Test environment setup and utilities
├── services/ # Unit tests for service classes
│ ├── AccountScheduler.test.js
│ ├── RiskStrategyService.test.js
│ └── TaskExecutionEngine.test.js
├── routers/ # Unit tests for API routers
│ └── SystemConfigRouter.test.js
├── integration/ # Integration tests
│ └── TaskWorkflow.test.js
├── package.json # Test dependencies and scripts
├── mocha.opts # Mocha configuration
├── .eslintrc.js # ESLint configuration for tests
└── README.md # This file
Test Categories
Unit Tests
- Service Tests: Test individual service classes in isolation
- Router Tests: Test API endpoints and HTTP request/response handling
- Model Tests: Test database models and their relationships
Integration Tests
- Workflow Tests: Test complete business workflows end-to-end
- System Integration: Test interaction between multiple services
- External API Integration: Test integration with external services
Running Tests
Prerequisites
cd backend/test
npm install
Test Commands
# Run all tests
npm test
# Run unit tests only
npm run test:unit
# Run integration tests only
npm run test:integration
# Run router tests only
npm run test:routers
# Run tests with coverage report
npm run test:coverage
# Run tests in watch mode (for development)
npm run test:watch
# Lint test code
npm run lint
# Fix lint issues automatically
npm run lint:fix
Test Environment
Database
- Uses SQLite in-memory database for fast, isolated testing
- Test data is created and cleaned up automatically
- Database schema is synchronized before each test run
Redis
- Uses
ioredis-mockfor Redis simulation - No external Redis instance required for testing
- All Redis operations are mocked and isolated
External Dependencies
- Telegram API calls are mocked using Sinon.js
- External HTTP requests are stubbed to avoid network dependencies
- File system operations use temporary directories
Writing Tests
Test File Structure
const { expect } = require('chai');
const TestSetup = require('../setup');
const ServiceUnderTest = require('../../src/service/ServiceUnderTest');
describe('ServiceUnderTest', function() {
let service;
let testDb;
before(async function() {
this.timeout(10000);
await TestSetup.setupDatabase();
await TestSetup.setupRedis();
await TestSetup.createTestData();
testDb = TestSetup.getTestDb();
service = new ServiceUnderTest();
});
after(async function() {
await TestSetup.cleanup();
});
describe('Feature Group', function() {
it('should test specific behavior', async function() {
// Test implementation
});
});
});
Best Practices
- Isolation: Each test should be independent and not rely on other tests
- Cleanup: Always clean up resources after tests complete
- Mocking: Mock external dependencies to ensure tests are fast and reliable
- Assertions: Use descriptive assertions with clear error messages
- Async/Await: Use async/await for asynchronous operations
- Timeouts: Set appropriate timeouts for long-running tests
Test Data
The setup.js file provides methods for creating consistent test data:
await TestSetup.createTestData(); // Creates accounts, tasks, and rules
const testAccount = await TestSetup.createTestAccount(customData);
const testTask = await TestSetup.createTestTask(customData);
Coverage Requirements
The test suite aims for:
- Lines: 80% minimum coverage
- Functions: 80% minimum coverage
- Branches: 70% minimum coverage
- Statements: 80% minimum coverage
Coverage reports are generated in the coverage/ directory when running npm run test:coverage.
Continuous Integration
Tests are designed to run in CI/CD environments:
- No external dependencies required
- Fast execution (< 2 minutes for full suite)
- Deterministic results
- Proper error reporting
Debugging Tests
Running Individual Tests
# Run specific test file
./node_modules/.bin/mocha services/AccountScheduler.test.js
# Run specific test case
./node_modules/.bin/mocha -g "should select optimal account"
Debug Mode
# Run with Node.js debugger
node --inspect-brk ./node_modules/.bin/mocha services/AccountScheduler.test.js
Verbose Output
# Run with detailed output
npm test -- --reporter json > test-results.json
Test Utilities
The test suite includes several utility functions:
TestSetup.setupDatabase(): Initialize test databaseTestSetup.setupRedis(): Initialize Redis mockTestSetup.createTestData(): Create sample dataTestSetup.cleanup(): Clean up all test resourcesTestSetup.getTestDb(): Get database instanceTestSetup.getTestRedis(): Get Redis instance
Common Issues
Database Sync Errors
- Ensure
TestSetup.setupDatabase()is called before tests - Check that models are properly imported
Redis Connection Issues
- Verify
TestSetup.setupRedis()is called - Ensure Redis operations are properly mocked
Timeout Issues
- Increase timeout for slow tests using
this.timeout(10000) - Consider optimizing test setup and teardown
Memory Leaks
- Always call
TestSetup.cleanup()inafter()hooks - Close all database connections and clear intervals
Contributing
When adding new tests:
- Follow the existing test structure and naming conventions
- Add appropriate test coverage for new features
- Update this README if adding new test categories
- Ensure all tests pass before submitting
- Run linting and fix any style issues
Performance
The test suite is optimized for speed:
- In-memory database for fast I/O
- Mocked external services
- Parallel test execution where possible
- Efficient setup and teardown procedures
Target execution times:
- Unit tests: < 30 seconds
- Integration tests: < 60 seconds
- Full suite: < 2 minutes