阿里云主机折上折
  • 微信号
Current Site:Index > Automated testing specifications

Automated testing specifications

Author:Chuan Chen 阅读数:56113人阅读 分类: 前端综合

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:

  1. Variable Naming: Use camelCase
  2. Constant Naming: Use UPPER_CASE with underscores
  3. Function Naming: Start with verbs (e.g., getUserInfo)
  4. Indentation: Consistently use 2 spaces
  5. 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:

  1. Test files should match the name of the tested file with a .test.js suffix.
  2. Each test case should have a clear description.
  3. 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:

  1. Test user interaction behavior, not implementation details.
  2. Avoid directly testing internal component state.
  3. 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:

  1. Test critical user workflows.
  2. Use meaningful test data.
  3. Avoid selectors that depend on implementation details.

Test Coverage Requirements

Different types of tests should have different coverage requirements:

  1. Unit tests: 80%+
  2. Component tests: 70%+
  3. 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:

  1. Use factory functions to create test data.
  2. Avoid hardcoding sensitive data.
  3. 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:

  1. Avoid duplicate code.
  2. Use clear descriptions.
  3. 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:

  1. Key path load times.
  2. Memory usage.
  3. 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:

  1. Keyboard navigation.
  2. Screen reader compatibility.
  3. 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:

  1. Use the same database version.
  2. Mock third-party services.
  3. 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:

  1. Test pass rate.
  2. Failure reasons.
  3. Relevant screenshots.
# Jest configuration
module.exports = {
  reporters: [
    'default',
    ['jest-html-reporters', {
      publicPath: './test-reports'
    }]
  ]
}

Test Maintenance Standards

Test code requires regular maintenance:

  1. Remove outdated tests.
  2. Update failing tests.
  3. 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

上一篇:错误监控方案

下一篇:文档编写规范

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.