Back to Review Hub 返回复习中心
DAY 2 第2天

🧪 TDD, Jest & File Persistence 🧪 Jest 测试、文件持久化与 TDD

Mastering Persistence, Logic, Sets, Regex and 100% Coverage. 掌握持久化、逻辑、Set、正则与 100% 测试覆盖率。

1. Data Persistence (JSON & File System) 1. 数据持久化 (JSON 与文件系统)

To keep data after the server stops, we must write it to a file. We use the fs module and JSON serialization. 为了在服务器停止后保留数据,我们必须将其写入文件。我们使用 fs 模块和 JSON 序列化。

import fs from 'fs';

// SAVING: Convert Object -> String -> File
const data = { score: 10, username: 'Evan' };
fs.writeFileSync('database.json', JSON.stringify(data));

// LOADING: File -> String -> Object
if (fs.existsSync('database.json')) {
  const raw = fs.readFileSync('database.json');
  const savedData = JSON.parse(raw);
}

⚠️ The Empty File Crash空文件崩溃陷阱

JSON.parse('') throws an error! Always ensure your file has valid JSON (e.g., {}) before parsing, or use a try-catch block. JSON.parse('') 会抛出错误!在解析之前,请始终确保文件包含有效的 JSON(例如 {}),或使用 try-catch 块。

2. Logic Power: Sets & Enums 2. 逻辑利器:Set 与 Enum

💎 Set: The Unique CollectorSet: 唯一收集器

Use new Set() when you need a list of items with NO duplicates. 当你需要一个没有重复项的列表时,使用 new Set()

const objections = new Set();
objections.add('HEARSAY');
objections.add('HEARSAY'); 
// Size is still 1!

🛡️ Enum: The Safety GuardEnum: 安全卫士

Enums prevent typos. Instead of string 'hearsay', use Objection.HEARSAY. Enum 防止拼写错误。不要用字符串 'hearsay',而要用 Objection.HEARSAY

3. String Kung-Fu: Parsing & Regex 3. 字符串功夫:解析与正则

Cleaning data is essential for logic like "Non-Responsive" objections. 清洗数据对于实现“答非所问 (Non-Responsive)”等逻辑至关重要。

// remove everything EXCEPT letters, numbers, and spaces
const clean = str.replace(/[^a-z0-9 ]/g, '');

// split by space to get words
const words = clean.split(' ').filter(w => w !== '');

// check intersection
const hasCommon = qWords.some(w => tWords.includes(w));
VISUALIZATION: SPLIT (Cutting the Rope)
"A?B?C".split('?')

A ✂️ B ✂️ C

Result: ["A", "B", "C"] (Length: 3)

🔬 Regex Syntax Breakdown 🔬 正则表达式语法详解

Symbol符号 Meaning含义 Example示例
^ Start of string OR "NOT" (if inside []) 字符串开头 或 “非” (当在 [] 内时) [^a-z] (Not a-z)
$ End of string 字符串结尾 \?$ (Ends with ?)
g Global flag (replace all occurrences) 全局标志 (替换所有出现) /a/g
+ One or more quantifiers 一个或多个 a+ (a, aa, aaa...)

3.5 Testing Like a Pro (Jest) 3.5 专业测试指南 (Jest)

Writing tests is about covering edge cases. Here are the trickiest patterns you need to know. 编写测试的关键在于覆盖边缘情况。以下是你需要知道的最棘手的模式。

💣 Testing Errors测试报错

Wrong: expect(fn()).toThrow()
错误: expect(fn()).toThrow()

Right: expect(() => fn()).toThrow()
正确: expect(() => fn()).toThrow()

Why? You must pass a function reference to Jest so IT can call it safely. If you call it yourself, it crashes before Jest sees it. 为什么?你必须把函数引用传给 Jest,让 Jest 来安全调用它。如果你自己调用,它在 Jest 看到之前就崩溃了。

🎯 Common Matchers常用匹配器

  • .toBe(val): Strict equality (===)
  • .toEqual(obj): Deep equality for objects/arrays
  • .toThrow(err): Checks error message substring
  • .toContain(item): Checks array/string inclusion
  • .not.toBe(val): Negation

4. Architecture Analysis (Evanweb Case Study) 4. 架构分析 (Evanweb 案例研究)

Analyzing this documentation site reveals key architectural patterns relevant to your 1531 projects. 分析当前的文档站点,揭示了与你的 1531 项目相关的关键架构模式。

Component组件 Implementation实现方式 Reasoning理由
Directory Structure /content/comp1531/, /src/styles/ Separation of Concerns. Content is separated from logic and styles. 关注点分离。内容与逻辑和样式完全分开。
Localization .en-content, .zh-content Classes Client-side toggling avoids needing two separate HTML pages (DRY Principal). 客户端切换避免了维护两个单独的 HTML 页面(DRY 原则)。
Design System Neubrutalism (CSS Variables) Consistent var(--nb-comp) usage ensures entire site updates easily if branding changes. 使用一致的 var(--nb-comp) 变量,确保若品牌变更,全站可轻松更新。

📝 Day 2 Mastery Quiz 📝 第2天复习测验

Test your skills in FS, JSON, and Logic implementation. 测试你在 FS、JSON 和逻辑实现方面的技能。

🎯 Start 40-Question Challenge 🎯 开始 40 题挑战