nov*_*ice 8 react-testing-library
我正在尝试使用 RTL 运行以下测试用例,并且测试失败并出现错误“TypeError:预期容器为元素、文档或文档片段但得到字符串。”。我尝试寻找解决方案,但找不到。
describe("Feedback Commponent",()=>{
it('should throw error when feedback textbox is empty', () => {
const { getByLabelText} = render(<Contact />);
fireEvent.change(getByLabelText('Feedback'), {
target: { value: '' },
});
fireEvent.blur(getByLabelText('Feedback'));
debug();
expect(getByTestId('feedback-error')).toBe(
'Please Enter Your Feedback'
);
});
});
Run Code Online (Sandbox Code Playgroud)
上面的代码片段假设测试反馈表单,具体来说只是反馈文本框,当它是空的并且当用户从文本框中失去焦点时,应该会出现一个错误,指出“请输入您的反馈”。
小智 10
似乎您直接从测试库中导入了 getByTestId 方法,而不是像使用 getByLabelText 那样从渲染中解构它。getByTestId,根据文档是:
getByTestId(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement
Run Code Online (Sandbox Code Playgroud)
所以它期望第一个参数是 HTML 容器,因此错误。一种解决方案是也解构 getByTestId:
const { getByLabelText, getByTestId } = render(<Contact />);
Run Code Online (Sandbox Code Playgroud)
另一种是按照文档的建议使用屏幕:
import { screen } from '@testing-library/react';
...
expect(screen.getByTestId('feedback-error')).toBe(
'Please Enter Your Feedback'
);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,第一个 'container' 参数被跳过,字符串 'feedback-error' 被视为 test id 'text' 参数。文档:https : //testing-library.com/docs/queries/bytestid
我通过将断言更改为解决了该问题
expect(getByText('Please Enter Your Feedback')).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)
从
expect(getByTestId('feedback-error')).toBe('Please Enter Your Feedback');
Run Code Online (Sandbox Code Playgroud)
我还注意到我有 setupTest.js 文件
import '@testing-library/jest-dom/extend-expect';
Missing ,它添加了用于在 DOM 节点上断言的自定义笑话匹配器,因此在添加上述更改后,我的测试用例通过了
| 归档时间: |
|
| 查看次数: |
4356 次 |
| 最近记录: |