Files
你的用户名 237c7802e5
Some checks failed
Deploy / deploy (push) Has been cancelled
Initial commit: Telegram Management System
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>
2025-11-04 15:37:50 +08:00

233 lines
6.3 KiB
Markdown

# 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
```bash
cd backend/test
npm install
```
### Test Commands
```bash
# 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-mock` for 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
```javascript
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
1. **Isolation**: Each test should be independent and not rely on other tests
2. **Cleanup**: Always clean up resources after tests complete
3. **Mocking**: Mock external dependencies to ensure tests are fast and reliable
4. **Assertions**: Use descriptive assertions with clear error messages
5. **Async/Await**: Use async/await for asynchronous operations
6. **Timeouts**: Set appropriate timeouts for long-running tests
### Test Data
The `setup.js` file provides methods for creating consistent test data:
```javascript
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
```bash
# 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
```bash
# Run with Node.js debugger
node --inspect-brk ./node_modules/.bin/mocha services/AccountScheduler.test.js
```
### Verbose Output
```bash
# Run with detailed output
npm test -- --reporter json > test-results.json
```
## Test Utilities
The test suite includes several utility functions:
- `TestSetup.setupDatabase()`: Initialize test database
- `TestSetup.setupRedis()`: Initialize Redis mock
- `TestSetup.createTestData()`: Create sample data
- `TestSetup.cleanup()`: Clean up all test resources
- `TestSetup.getTestDb()`: Get database instance
- `TestSetup.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()` in `after()` hooks
- Close all database connections and clear intervals
## Contributing
When adding new tests:
1. Follow the existing test structure and naming conventions
2. Add appropriate test coverage for new features
3. Update this README if adding new test categories
4. Ensure all tests pass before submitting
5. 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