如何通过使用React Hooks的Jest进行增量编写测试用例

时间:2020-11-04 15:37:36

标签: reactjs jestjs react-hooks react-testing-library

我正在学习如何使用Jest编写测试用例。在我的项目中,我有一个按钮。如果我单击该按钮,则在段落中它将显示我单击了多少次。请告诉我如何为该组件编写测试用例。

这是App.js

import React from 'react';
import './App.css';
import Button from './Button/Button';

const App = () => {
  return (
    <div className='container'>
      <div className='row'>
        <div className='col-12'>
          <Button></Button>
        </div>
      </div>
    </div>
  )
}

export default App

这是Button.js

import React, { useState } from 'react';
import './Button.css';

const Button = () => {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    )
}

export default Button

Button.test.js中没有任何内容

这是package.json

{
  "name": "one",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.1",
    "@testing-library/user-event": "^12.2.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.0",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

1 个答案:

答案 0 :(得分:0)

单元测试解决方案:

app:generateReleaseJavadoc

Button.jsx

import React, { useState } from 'react'; const Button = () => { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default Button;

Button.test.jsx

单元测试结果:

import React from 'react';
import Button from './Button';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

describe('64683116', () => {
  it('should pass', () => {
    const { container } = render(<Button></Button>);
    expect(container.querySelector('p')).toHaveTextContent('You clicked 0 times');
    expect(container.querySelector('button')).toHaveTextContent('Increment');
    fireEvent.click(container.querySelector('button'));
    expect(container.querySelector('p')).toHaveTextContent('You clicked 1 times');
    fireEvent.click(container.querySelector('button'));
    expect(container.querySelector('p')).toHaveTextContent('You clicked 2 times');
  });
});

源代码:https://stackoverflow.com/a/29164335/10365305