You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Jest测试用例中检查文本内容的指定顺序?

How to Verify "Teacher" Comes Before "Student" in Text Content with Jest & React Testing Library

Got it, let's work through this together. You already have your target element grabbed by ID—now we just need to make sure "Teacher" always shows up before "Student" in its text. Here are two solid, easy-to-implement approaches:

Approach 1: Compare Substring Index Positions

This method is straightforward: get the starting index of both keywords and assert that "Teacher" comes first numerically. It’s clear and also doubles down on verifying both keywords exist in the text.

const getId = queryByAttribute.bind(null, 'id'); 
const result = getById(component.container, 'student-details-page');

const text = result.textContent;

// Check that Teacher's first occurrence is earlier than Student's
expect(text.indexOf('Teacher')).toBeLessThan(text.indexOf('Student'));

Why this works:

  • indexOf() returns the first position of the substring in the text. If "Teacher" is before "Student", its index will be a smaller number.
  • If either keyword is missing from the text, indexOf() returns -1, which will automatically fail the test—so you get two checks in one.

Approach 2: Use a Regular Expression

For a more concise solution, you can use a regex pattern to match "Teacher" followed by any characters (including none) and then "Student". Jest’s toMatch() matcher handles this perfectly.

const getId = queryByAttribute.bind(null, 'id'); 
const result = getById(component.container, 'student-details-page');

// Assert the text follows the required order pattern
expect(result.textContent).toMatch(/Teacher.*Student/);

Why this works:

  • The regex Teacher.*Student matches any string where "Teacher" appears before "Student", regardless of what’s in between them.
  • Like the first approach, this also ensures both keywords are present—if either is missing, the regex won’t match, and the test fails.

Quick Note for Your Specific Text

Even though your textContent has condensed text like Details:TeacherJin;SugaStudentDaphne (while the UI shows spaced text), both methods will still work. They’re looking for the exact substrings "Teacher" and "Student", so surrounding characters don’t throw off the check.

内容的提问来源于stack exchange,提问作者minsuga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:37:31