【问题标题】:How to test a button its text changes depending on useState()如何根据 useState() 测试按钮的文本变化
【发布时间】: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


    【解决方案1】:

    以下是步骤:

    • 获取带有copy 文本的按钮并确保它在文档中
    • 单击该按钮 => 文本应更改,因此...
    • 获取带有copied!文本的按钮并确保它在文档中
    import { render, screen } from '@testing-library/react';
    import userEvent from "@testing-library/user-event";
    
    import ShortedLink from "../ShortedLink";
    
    describe('it should work', () => {
      it('should work', async () => {
        render(<ShortedLink />);
    
        const copyButton = screen.getByRole('button', { name: 'copy' });
        expect(copyButton).toBeInTheDocument();
    
        await userEvent.click(copyButton);
    
        const copiedButton = screen.getByRole('button', { name: 'copied!' });
        expect(copiedButton).toBeInTheDocument();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多