如何在React Jest测试用例中检查文本内容的指定顺序?
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.*Studentmatches 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

