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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
量子位
S
Secure Thoughts
G
GRAHAM CLULEY
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
S
Security Affairs
Help Net Security
Help Net Security
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
H
Heimdal Security Blog
W
WeLiveSecurity
C
Check Point Blog

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
Making your UI tests resilient to change
2019-10-07 · via Kent C. Dodds Blog

You're a developer and you want to avoid shipping a broken login experience, so you're writing some tests to make sure you don't. Let's get a quick look at an example of such a form:

Login form from the Bookshelf App

const form = (
	<form onSubmit={handleSubmit}>
		<div>
			<label htmlFor="username">Username</label>
			<input id="username" className="username-field" />
		</div>
		<div>
			<label htmlFor="password">Password</label>
			<input id="password" type="password" className="password-field" />
		</div>
		<div>
			<button type="submit" className="btn">
				Login
			</button>
		</div>
	</form>
)

Now, if we were to test this form, we'd want to fill in the username, password, and submit the form. To do that properly, we'd need to render the form and query the document to find and operate on those nodes. Here's what you might try to do to make that happen:

const usernameField = rootNode.querySelector('.username-field')
const passwordField = rootNode.querySelector('.password-field')
const submitButton = rootNode.querySelector('.btn')

And here's where the problem comes in. What happens when we add another button? What if we added a "Sign up" button before the "Login" button?

const form = (
	<form onSubmit={handleSubmit}>
		<div>
			<label htmlFor="username">Username</label>
			<input id="username" className="username-field" />
		</div>
		<div>
			<label htmlFor="password">Password</label>
			<input id="password" type="password" className="password-field" />
		</div>
		<div>
			<button type="submit" className="btn">
				Sign up
			</button>
			<button type="submit" className="btn">
				Login
			</button>
		</div>
	</form>
)

Whelp, that's going to break our tests. But that'd be pretty easy to fix right?

// change this:
const submitButton = rootNode.querySelector('.btn')
// to this:
const submitButton = rootNode.querySelectorAll('.btn')[1]

And we're good to go! Well, if we start using CSS-in-JS to style our form and no longer need the username-field and password-field class names, should we remove those? Or do we keep them because our tests use them? Hmmmmmmm..... 🤔

So how do we write resilient selectors?

Given that "the more your tests resemble the way your software is used, the more confidence they can give you", it would be wise of us to consider the fact that our users don't care what our class names are.

So, let's imagine that you have a manual tester on your team and you're writing instructions for them to test the page for you. What would those instructions say?

  1. get the element with the class name username-field
  2. ...

"Wait," they say. "How am I going to find the element with the class name username-field?"

"Oh, just open your devtools and..."

"But our users wont do that. Why don't I just find the field that has a label that says username?"

"Oh, yeah, good idea."

This is why Testing Library has the queries that it does. The queries help you to find elements in the same way that users will find them. These queries allow you to find elements by their role, label, placeholder, text contents, display value, alt text, title, test ID.

That's actually in the order of recommendation. There certainly are trade-offs with these approaches, but if you wrote out instructions for a manual tester using these queries, it would look something like this:

  1. Type a fake username in the input labeled username
  2. Type a fake password in the input labeled password
  3. Click on the button that has text sign in
const usernameField = rootNode.getByRole('textbox', { name: /username/i })
const passwordField = rootNode.getByLabelText('password')
const submitButton = rootNode.getByRole('button', { name: /sign in/i })

And that would help to ensure that you are testing your software as closely to how it's used as possible. Giving you more value from your test.

What's with the data-testid query?

Sometimes you can't reliably select an element by any of the other queries. For those, it's recommended to use data-testid (though you'll want to make sure that you're not forgetting to use a proper role attribute or something first).

Many people who hit this situation, wonder why we don't include a getByClassName query. What I don't like about using class names for my selectors is that normally we think of class names as a way to style things. So when we start adding a bunch of class names that are not for that purpose it makes it even harder to know what those class names are for and when we can remove class names.

And if we simply try to reuse class names that we're already just using for styling then we run into issues like the button up above. And any time you have to change your tests when you refactor or add a feature, that's an indication of a brittle test. The core issue is that the relationship between the test and the source code is too implicit. We can overcome this issue if we make that relationship more explicit.

If we could add some metadata to the element we're trying to select that would solve the problem. Well guess what! There's actually an existing API for this! It's data- attributes! For example:

function UsernameDisplay({ user }) {
	return <strong data-testid="username">{user.username}</strong>
}

And then our test can say:

const usernameEl = getByTestId('username')

This is great for end to end tests as well. So I suggest that you use it for that too! However, some folks have expressed to me concern about shipping these attributes to production. If that's you, please really consider whether it's actually a problem for you (because honestly it's probably not as big a deal as you think it is). If you really want to, you can compile those attributes away with babel-plugin-react-remove-properties.

Conclusion

You'll find that testing your applications in a way that's similar to how your software is used makes your tests not only more resilient to changes, but also provide more value to you. If you want to learn more about this, then I suggest you read more in my blog post Testing Implementation Details.

I hope this is helpful to you. Good luck!