Automated testing specifications
Engineering standards and automated testing standards are two indispensable aspects of frontend development. Engineering standards improve code maintainability and team collaboration efficiency, while automated testing standards ensure code quality and functional stability. Combining the two can significantly enhance development efficiency and project delivery quality.
The Necessity of Engineering Standards
Engineering standards are the foundation of team collaboration, unifying code style, directory structure, and development workflows. Without standardized engineering, team collaboration can become chaotic, and code maintenance costs can skyrocket. For example, different developers might use different indentation styles (spaces or tabs), leading to inconsistent styling issues in the codebase.
// Non-standard example: Mixed indentation
function foo() {
console.log('hello');
console.log('world'); // Tab indentation
}
By introducing engineering tools (e.g., ESLint, Prettier), code can be automatically formatted, and team-agreed standards can be enforced.
// Standard example: Unified indentation (2 spaces)
function foo() {
console.log('hello');
console.log('world');
}
Code Style Standards
Code style standards include naming conventions, indentation rules, quote usage, and other details. Here are some common standards:
- Variable Naming: Use camelCase
- Constant Naming: Use UPPER_CASE with underscores
- Function Naming: Start with verbs (e.g.,
getUserInfo
) - Indentation: Consistently use 2 spaces
- Quotes: Consistently use single quotes (
'
)
// Standard example
const MAX_COUNT = 10;
function getUserInfo(userId) {
return {
id: userId,
name: 'John Doe'
};
}
Directory Structure Standards
A clear directory structure improves project maintainability. A typical frontend project directory might look like this:
src/
├── assets/ # Static assets
├── components/ # Shared components
├── pages/ # Page components
├── store/ # State management
├── utils/ # Utility functions
├── styles/ # Global styles
└── index.js # Entry file
Commit Message Standards
Git commit messages should also follow standards. The Conventional Commits specification is recommended:
feat: Add user login feature
fix: Resolve homepage loading issue
docs: Update README documentation
chore: Update dependencies
The Necessity of Automated Testing Standards
Automated testing is a critical tool for ensuring code quality and quickly identifying regression issues. Frontend testing typically includes unit tests, component tests, and end-to-end tests.
Unit Testing Standards
Unit tests target the smallest testable units (usually functions). Example using Jest:
// utils/sum.js
function sum(a, b) {
return a + b;
}
// tests/sum.test.js
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Unit testing standards:
- Test files should match the name of the tested file with a
.test.js
suffix. - Each test case should have a clear description.
- Test coverage should exceed 80%.
Component Testing Standards
Component tests verify UI component behavior. Example using React Testing Library:
// components/Button.jsx
function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
}
// tests/Button.test.jsx
import { render, screen, fireEvent } from '@testing-library/react';
test('calls onClick when clicked', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Click me</Button>);
fireEvent.click(screen.getByText('Click me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
Component testing standards:
- Test user interaction behavior, not implementation details.
- Avoid directly testing internal component state.
- Simulate user workflows.
End-to-End Testing Standards
End-to-end tests validate the entire application workflow. Example using Cypress:
// tests/e2e/login.spec.js
describe('Login', () => {
it('should login successfully', () => {
cy.visit('/login');
cy.get('#username').type('testuser');
cy.get('#password').type('password123');
cy.get('button[type="submit"]').click();
cy.url().should('include', '/dashboard');
});
});
End-to-end testing standards:
- Test critical user workflows.
- Use meaningful test data.
- Avoid selectors that depend on implementation details.
Test Coverage Requirements
Different types of tests should have different coverage requirements:
- Unit tests: 80%+
- Component tests: 70%+
- End-to-end tests: 50%+
Generate coverage reports with Jest:
// package.json
{
"scripts": {
"test:coverage": "jest --coverage"
}
}
CI/CD Integration Standards
Automated tests should be integrated into CI/CD pipelines to ensure tests run on every commit. Example GitHub Actions configuration:
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm test
- run: npm run test:coverage
Test Data Management Standards
Test data management is a key part of testing standards:
- Use factory functions to create test data.
- Avoid hardcoding sensitive data.
- Test data should be easy to maintain.
// tests/factories/user.js
export function createUser(overrides = {}) {
return {
id: 1,
name: 'Test User',
email: 'test@example.com',
...overrides
};
}
Test Code Quality Standards
Test code should also adhere to quality standards:
- Avoid duplicate code.
- Use clear descriptions.
- Keep tests independent.
// Not recommended: Duplicate code
test('adds 1 + 2', () => {
expect(sum(1, 2)).toBe(3);
});
test('adds 2 + 3', () => {
expect(sum(2, 3)).toBe(5);
});
// Recommended: Parameterized tests
describe.each([
[1, 2, 3],
[2, 3, 5]
])('sum(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(sum(a, b)).toBe(expected);
});
});
Performance Testing Standards
Performance testing should be part of the automated testing process:
- Key path load times.
- Memory usage.
- Rendering performance.
// tests/performance/homepage.spec.js
describe('Homepage Performance', () => {
it('should load within 2 seconds', () => {
const start = performance.now();
cy.visit('/');
cy.get('#main-content').should('be.visible');
const end = performance.now();
expect(end - start).to.be.lessThan(2000);
});
});
Accessibility Testing Standards
Accessibility testing ensures the application is usable by all users:
- Keyboard navigation.
- Screen reader compatibility.
- Color contrast.
// tests/a11y/button.spec.js
describe('Button Accessibility', () => {
it('should be focusable', () => {
cy.visit('/');
cy.get('button').first().focus();
cy.focused().should('have.attr', 'role', 'button');
});
});
Test Environment Management Standards
Test environments should closely match production:
- Use the same database version.
- Mock third-party services.
- Manage environment variables.
// cypress.config.js
module.exports = {
e2e: {
baseUrl: process.env.TEST_URL || 'http://localhost:3000'
}
}
Test Reporting Standards
Test reports should include sufficient information:
- Test pass rate.
- Failure reasons.
- Relevant screenshots.
# Jest configuration
module.exports = {
reporters: [
'default',
['jest-html-reporters', {
publicPath: './test-reports'
}]
]
}
Test Maintenance Standards
Test code requires regular maintenance:
- Remove outdated tests.
- Update failing tests.
- Refactor duplicate tests.
// Periodically check test validity
describe('Legacy Feature', () => {
it.skip('should be removed in next version', () => {
// Marked for skipping, pending removal
});
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn