【问题标题】:How to test checkboxes with react-test-library如何使用 react-test-library 测试复选框
【发布时间】:2020-12-15 15:01:08
【问题描述】:

我正在使用最新版本的 create-react-app(在 package.json 中,“react”:“^17.0.1”)

我正在尝试使用 react-test-library 来测试一个应用程序,其中检查复选框会增加一个计数器。 我已经将问题归结为我可以管理的最完美的形式。我试过keyDown,点击...

文本需要'2'并接收'0':

组件文件:

import React, { useEffect, useState  } from "react";

function App3() {
  const [counter, setCounter]= useState(0);
  const handleClickInCheckbox = (ev) => {
  setCounter(2)
  };

  return (
    <div className="App">
      <input type="checkbox" onChange={handleClickInCheckbox} id="chkbx" data-testid="ch1" ></input>
      <h1 data-testid="h1" >{counter}</h1>
    </div>
  );
}

export default App3;

测试文件:

import React from 'react';
import { render, act,  screen, fireEvent,  getByRole} from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import App from '../App3'

describe ('app', () => {
      test('checking boxes should increment counter',
      ()=>  {
             act( 
                   ()=>{
                    render (<App /> );
               const ch1 =   screen.getByTestId('ch1')
               const h1 =   screen.getByTestId('h1')
               ch1.focus();
               fireEvent.keyDown(document.activeElement)
               fireEvent.keyDown(screen.getByTestId('ch1'))
                 expect(h1).toHaveTextContent('2');
                 }
                )
             }
 )
})

我尝试使用 jest-environment-jsdom-sixteen,但这并没有改变任何东西 在 package.json 中:

"test": "react-scripts test --env=jest-environment-jsdom-sixteen",

【问题讨论】:

    标签: reactjs jestjs create-react-app react-testing-library jsdom


    【解决方案1】:

    相关事件.click,但你也不应该在整个测试中加上act

    describe ('app', () => {
      test('checking boxes should increment counter', () => {
        render(<App />);
        const ch1 = screen.getByTestId('ch1')
        const h1 = screen.getByTestId('h1')
                   
        act(() => {
          fireEvent.click(screen.getByTestId('ch1'))
        })
        
        expect(h1).toHaveTextContent('2')
      })
    })
    

    在这种情况下,它实际上在没有 act 的情况下也可以工作,因为没有异步发生,但是当您确实需要 act 时,它应该关注您期望状态发生变化的点。

    【讨论】:

    • 将“期望”移到“行为”之外确实是让测试通过的原因
    猜你喜欢
    • 2020-08-03
    • 2021-05-27
    • 2019-08-29
    • 2020-05-14
    • 2021-11-30
    • 2019-05-21
    • 2019-10-30
    • 2021-02-11
    • 2022-08-04
    相关资源
    最近更新 更多