ไลบรารีการทดสอบการตอบสนอง: จับคู่จำนวนปุ่ม

Aug 16 2020

ฉันได้สร้างแอปโดยใช้ create-react-app ด้านล่างนี้คือส่วนประกอบตัวนับและไฟล์ทดสอบของฉัน ฉันกำลังพยายามสร้างการทดสอบสำหรับปุ่มคงที่สามปุ่มที่ฉันมีในส่วนประกอบของฉัน การทดสอบครั้งแรกทำงานได้ดีในขณะที่การทดสอบครั้งที่ 2 ให้ข้อผิดพลาดที่ระบุไว้ด้านล่าง

ส่วนประกอบปฏิกิริยา:

    import React from "react";
    import PropTypes from "prop-types";
    import classes from "./Counter.module.css";
    function Counter(props) {
      return (
        <div className={classes.Wrapper}>
          <div>
            <p>
              Click Counter -  {props.value}
            </p>
          </div>
          <div>
            <button onClick={props.counterIncrement} className={classes.custButton} name="first"> Increment </button>
            {/* <button onClick={props.counterDecrement} className={classes.custButton}> Decrement </button>
            <button onClick={props.resetCounter} className={classes.custButton}> Reset </button> */}
          </div>
        </div>
      );
    }
    Counter.propTypes = {
      value: PropTypes.number,
      clickHandler: PropTypes.func,
    };
    export default Counter;

ทดสอบไฟล์:

    import React from 'react'
    import {render, fireEvent, screen, cleanup} from '@testing-library/react'
    
    import Counter from "./Counter";
    
    
    afterEach(cleanup);
    
    describe('Counter', () => {
        test('renders counter value 10', () => {
          render(<Counter />);
          //screen.debug();
          expect(screen.getByText(/Click Counter -/)).toBeInTheDocument();
        })
    
    })
    
    test('renders three buttons', () => {
        render(<Counter />);
        const items = screen.findAllByRole('button');
        expect(items).toHaveLength(3);
      })

ข้อความผิดพลาด:

FAIL src / components / Counter / Counter.test.js ●แสดงผลปุ่มสามปุ่มคาดว่า (ได้รับ) .toHaveLength (คาดว่า) ข้อผิดพลาด Matcher: ค่าที่ได้รับต้องมีคุณสมบัติความยาวซึ่งค่าต้องเป็นตัวเลขที่ได้รับมีประเภท: วัตถุที่ได้รับมีค่า: {} 19 | แสดงผล (); 20 | const items = screen.findAllByRole ('ปุ่ม'); > 21 | คาดหวัง (รายการ) .toHaveLength (3); | ^ 22 | }) ที่ Object..test (src / components / Counter / Counter.test.js: 21: 19) *

คำตอบ

2 DobbyDimov Aug 16 2020 at 01:05

ในตัวอย่างที่คุณให้มาคุณกำลังใช้.findAllByRole('button')ซึ่งส่งคืนคำสัญญาและต้องรอดังนี้

test('renders three buttons', async () => {
  render(<Counter />)
  const items = await screen.findAllByRole('button')
  expect(items).toHaveLength(3)
})

อีกวิธีหนึ่งคือการใช้.getAllByRole('button')ซึ่งในกรณีนี้คุณสามารถยืนยันผลลัพธ์ได้ทันที