【发布时间】:2022-11-12 07:09:21
【问题描述】:
这是我的 jsx,当单击按钮时,状态会发生变化,按钮文本也会发生变化 `
const [copied, setCopied] = useState(false);
<button
className={`btn ${copied ? 'copy copied' : 'copy'}`}
onClick={() => {
setCopied(true);
navigator.clipboard.writeText(shortedLink);
}}
>
{copied ? 'copied!' : 'copy'}
</button>
` 如何使用 Jest 和 RTL 测试此条件文本
我是单元测试的新手,我已经尝试过这两种解决方案,但两种都失败了 -- 第一个说 -- 值必须是 HTMLElement 或 SVGElement。收到的值:null
-- 第二个说 -- 无法读取未定义的属性(读取“类型”) `
it('should change the text of the button when clicked', async () => {
user.setup();
render(<ShortedLink />);
const copyBtn = screen.getByRole('button', {
name: 'copy'
});
const copiedBtn = screen.queryByRole('button', {
name: 'copied!'
});
expect(copyBtn).toBeInTheDocument('copy');
expect(copiedBtn).toBe(null);
await user.click(copyBtn);
expect(copiedBtn).toBeInTheDocument();
});
and
it('should change the text of the button when clicked', async () => {
user.setup();
render(<ShortedLink />);
const copyBtn = screen.getByRole('button', {
name: 'copy'
});
expect(copyBtn).toHaveTextContent('copy');
await user.click(copyBtn);
expect(copyBtn).toHaveTextContent('copied!'
【问题讨论】:
标签: reactjs unit-testing jestjs react-testing-library