Dha*_*ikh 7 reactjs jestjs react-testing-library
目前我正在这样做
getByText(/SomText/i);
Run Code Online (Sandbox Code Playgroud)
但我想创建一个函数并将一些文本作为参数传递。我试着这样做
let x = "/SomeText/i";
getByText(x);
Run Code Online (Sandbox Code Playgroud)
或者
getByText(`/${x}/i`);
Run Code Online (Sandbox Code Playgroud)
但没有一个选项有效。
小智 11
如果你有
const x = "Some string"
Run Code Online (Sandbox Code Playgroud)
要测试x使用正则表达式,
getByText(new RegExp(x, "i"))
Run Code Online (Sandbox Code Playgroud)
也许你正在寻找路过exact: false?
// Match a substring of Hello World
getByText(container, 'llo Worl', { exact: false }) // substring match
Run Code Online (Sandbox Code Playgroud)
您还可以传递自己的匹配自定义函数。
getByText(container, (content, element) => content.startsWith('Hello'))
Run Code Online (Sandbox Code Playgroud)
https://testing-library.com/docs/dom-testing-library/cheatsheet#text-match-options
欢迎来到SO!
我还没有测试过这个,但似乎 getByText 需要一个正则表达式:
getByText(/SomeText/i);
Run Code Online (Sandbox Code Playgroud)
作为参数,而不是您在这里放置的字符串:
let x = "/SomeText/i";
Run Code Online (Sandbox Code Playgroud)
如果您像这样从字符串创建正则表达式,您的代码可以工作吗?
let x = new RegExp("/SomeText/i");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5611 次 |
| 最近记录: |