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

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

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? When I follow TDD 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 Profile a React App for Performance
The Merits of Mocking
2018-11-05 · via Kent C. Dodds Blog

The more your tests resemble the way your software is used, the more confidence they can give you.  — me

One of the biggest challenges people face with testing is knowing what to test. There are lots of reasons for that, but one big, flashing-lights reason is mocking. Many people don't know when to add a mock version of code or have their test run the actual code directly. These are challenges I'll help you work through in the JavaScript Mocking Fundamentals module of my Testing JavaScript course.

Mocking lets you fake it so you can make it. If you couldn't have a fake version of certain modules or services, testing the checkout process of an app would cost you a lot of money in credit card fees. Talk about paying a high price for confidence! 🤑 So instead, we make a fake version of that credit card charging service to avoid paying the fees.

But mocking comes with a cost of its own.

Mocking severs the real-world connection between what you're testing and what you're mocking. Even if we have confidence that our code works with our fake version of the credit card service, we can't have 100% confidence that our code will work in production with the real version of the credit card service.

When you mock something, you're making a trade-off. You're trading confidence for something else. For me, that something else is usually practicality — meaning I wouldn't be able to test this thing at all, or it may be pretty difficult/messy, without mocking. (Like in our credit card example.)

In my UI unit and integration tests, I have a rule. I never make actual network calls; instead, I'll mock the server response by mocking the module responsible for making the network calls. I'll also mock animation libraries to avoid waiting for animations before elements are removed from the page. Other than that, most of my UI tests are using the real production code. For E2E tests, I avoid mocking anything (with the exception of the backend hitting fake or test services and not actual credit card services, for example).

Saving a few milliseconds per test? That's not a good reason to mock. People like shallow rendering — component mocking to the max — because it's faster. That's true, but we're talking milliseconds faster. If it takes a long time to render your entire component tree, sounds to me like you have a real performance bug in your software that needs to be addressed. I realize that time adds up (50ms per test * 1000 tests = 50 seconds). But the less you mock, the fewer tests you need, and trading confidence for a minute or two faster test suite is a bad trade. 😵

There's a time and a place for mocking. And when you need to mock, Jest makes it easy with some really sweet mocking utilities. In testingjavascript.com I'll show you how to implement some of Jest's mocking capabilities in raw node so you can get an idea of what's going on. It's brilliant. Here's an example of simulating Jest's inline mock functionality in pure node:

function fn(impl = () => {}) {
	const mockFn = (...args) => {
		mockFn.mock.calls.push(args)
		return impl(...args)
	}
	mockFn.mock = { calls: [] }
	return mockFn
}

const utilsPath = require.resolve('#app/utils')
require.cache[utilsPath] = {
	id: utilsPath,
	filename: utilsPath,
	loaded: true,
	exports: {
		getWinner: fn((p1, p2) => p1),
	},
}

Now, any code that requires that utils module will get the mock function version of that module.

It's not quite as capable as Jest's inline mocking abilities, but we'll cover that in more hands-on detail in the JavaScript Mocking Fundamentals module of the course!

See you there.