Skip to content

TDD 练习: 构建字符串 Formatter

简单 约 35 分钟

你将构建什么

字符串 formatter utility 使用方法 for camelCase, kebab-情况, snake_case, and title 情况 conversion, 构建完全 using TDD Red-Green-Refactor cycle.

学习目标

  • 练习 TDD Red-Green-Refactor cycle
  • 编写 failing 测试之前 implementation
  • 编写 minimal code 到通过测试
  • Refactor 使用 confidence (测试 protect 你)
  • 构建 4 字符串格式化函数

前置要求

  • 已完成项目 1 or equivalent Jest experience
  • 理解的 字符串方法 in JavaScript
  • Familiarity 使用 TDD 概念

步骤

  1. 1

    RED: 编写首先 failing 测试

    创建 stringFormatter.测试.js. 编写测试 for camelCase conversion 之前任何 implementation exists. 运行它 — 它应该失败 (Red phase).

    代码
    const { toCamelCase } = require('./stringFormatter');
    
    test('converts space-separated to camelCase', () => {
      expect(toCamelCase('hello world')).toBe('helloWorld');
    });

    预期结果

    测试失败使用 'Cannot 查找模块' or 'toCamelCase 是不 函数'.

  2. 2

    GREEN: 编写 minimal code 到通过

    创建 stringFormatter.js 使用 simplest implementation 那个通过测试.

    代码
    function toCamelCase(str) {
      return str.split(' ').map((word, i) =>
        i === 0 ? word : word[0].toUpperCase() + word.slice(1)
      ).join('');
    }
    module.exports = { toCamelCase };

    预期结果

    测试通过 (Green phase).

  3. 3

    RED→GREEN: 添加 kebab-情况

    编写 failing 测试 for toKebabCase, 然后 implement 它. Follow cycle: 编写测试 (red), implement (green).

    代码
    // Test (RED)
    test('converts to kebab-case', () => {
      expect(toKebabCase('Hello World')).toBe('hello-world');
    });
    
    // Implementation (GREEN)
    function toKebabCase(str) {
      return str.toLowerCase().replace(/\s+/g, '-');
    }

    预期结果

    新测试通过之后 implementation.

  4. 4

    REFACTOR: Improve code

    现在那个测试通过, refactor code for clarity. Extract shared logic, improve 变量 names. 运行测试之后每个更改到 ensure 无 breaks.

    预期结果

    Code 是 cleaner, 所有测试 still 通过.

  5. 5

    Continue TDD for snake_case and title 情况

    Repeat Red-Green-Refactor cycle for toSnakeCase and toTitleCase. 编写测试首先, watch 它失败, implement, watch 它通过, 然后 refactor.

    预期结果

    所有 four 函数是 implemented 使用完整测试 coverage.

自己动手试试

你学到了什么

你 experienced TDD workflow firsthand: 编写测试首先 forces 你到 think 关于接口之前 implementation. Red-Green-Refactor cycle gives 你 confidence — 测试 protect 你期间 refactoring and document expected behavior.

相关资源

相关课程

相关练习

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题