惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
When I follow TDD
Kent C. Dodds 🏹 @kentcdodds · 2020-06-29 · via Kent C. Dodds Blog

Test-driven development (aka TDD) is a three-step process. It's often referred to as the "red, green, refactor cycle"

TDD Cycle

Here's the way it works:

  • 🚨 Red: Write a test for the function/module you're going to create before it exists/supports the feature you're adding. This gives you a test that fails (you get a "red" error message).
  • Green: Implement just enough code to get that test passing (you get a "green" success message).
  • 🌀 Refactor: Look over the code you have written and refactor it to ensure it's well-written, as easy as possible to read/understand, and well-designed. (The cool thing with this step is that you now have a test in place that will tell you if you break something as you refactor).
  • 🔁 Repeat: It's a cycle, after all 😉 Keep going until you've finished implementing everything you need to.

There's a bunch of nuance to this approach and some people can get down-right religious about the whole thing. I try to take a practical approach to TDD and only apply it in situations where I feel it could be actually beneficial.

I write tests following TDD when it makes sense

16 248

But that's the big question: "when does TDD make sense?" It's really an intuition you develop and frankly has a lot to do with your comfort and experience with TDD, but here are a few examples of situations where I follow the red-green-refactor cycle of TDD.

Fixing a bug

When I've got a bug to fix, I love reproducing that bug with a test before fixing it. Doing this gives me a huge amount of confidence that I understand the cause of the bug in the first place and when I get the test to green, I know that I've actually fixed the bug and not just tested around the problem.

I'd say that I follow this approach 90% of the time in software I care about (and therefore have tests for). Especially in my open source libraries. Here's an example of such a test.

Fixing a bug? Try TDD.

Pure functions

I don't test all my pure utility functions (I cover most of those with integration tests), but if I've got a utility function of sufficient complexity to need isolated unit tests, then that's another great situation that's well suited for TDD. With these kinds of functions, you often have a pretty well-defined set of inputs and outputs based on the requirements you have for the code.

I think most of us have experienced situations like this (and you will soon if you haven't yet). When I was at PayPal, I needed to format the amount input field as the user typed in the amount of money they wanted to send. The logic for that was surprisingly more complex that you might think thanks to currency precision (some currencies don't have a concept of a decimal amount). Formatting a currency amount like this was a perfect situation for TDD because the possible inputs and required outputs were easy to come up with.

Another good set of examples of this (that's also open source), are the tests for my project rtl-css-js.

Writing a pure utility function? Try TDD.

Well defined user interfaces

It's only since I created Testing Library that I thought TDD of user interfaces was really reasonably possible on the web. This is because:

It's pointless to TDD when you test implementation details.

Honestly, it's pointless to test at all if you're testing implementation details (they're just slowing you down). Part of the point of using TDD is to help you think about the thing you're building from the outside, without thought for the implementation, so when you get to implementing things you don't get lost in the details of the code and can keep the high-level goal in mind. It helps you when you only know what you're building, but not how you're going to build it.

The most popular tools before Testing Library (in all it's varieties), allowed (and encouraged) you to test implementation details. So to use TDD, that required that you knew (for example) you were going to create a private method called makeDonation and that it would be called with amount and currency (and not the other way around). So TDD always felt like a pointless waste of time. Just going through the motions.

However, since Testing Library allows you to focus on the user's experience, rather than the implementation, you can follow TDD when building UIs that have a well-defined design and user experience.

For an example, here's a video I made a few years ago to demonstrate this with a login component. It is a few years old, so things are even easier these days. If you're looking for something like this, just more polished and up to date, then grab a license to TestingJavaScript.com and you can watch me teach you TDD in 8 high value-to-minute videos (in addition to TONS more stuff).

Building a well-defined UI? Try TDD.

Conclusions

That's pretty much it for me. I'm sure other people have valid situations where they apply TDD practices and that's fine.

If I'm just doing some exploratory coding (which I do a lot) or messing around then I won't bother following TDD and I'll only add tests when I'm pleased with the direction things have taken. Incidentally, this is the same approach I follow any time I've used a type system (like Flow or TypeScript). This is also the approach I follow with making abstractions.

Writing tests, adding types, and making abstractions for your code are investments in what you've built. Making those investments is pointless if you aren't certain that what you're building is going to be around in the long-term. Those investments can also be ill-advised if you're uncertain what form what you're building will take by the time you're finished. And to take things further, the sunk cost falacy of these investments can influence you in a way that results in a sub-optimal solution.

Good luck!