如何使用 Jest 测试 React 组件的 onClick 行?

Gar*_*yer 2 javascript testing unit-testing reactjs jestjs

我正在学习 React,目前正在尝试 Jest/testing。我正在对一个小项目进行测试,我希望获得 100% 的代码覆盖率。这就是我所拥有的。

成分:

import React from 'react';

function Square(props) {
    const className = props.isWinningSquare ?
        "square winning-square" :
        "square";
    return (
        <button
            className={className}
            onClick={() => props.onClick()}
        >
            {props.value}
        </button>
    );
}

export default Square
Run Code Online (Sandbox Code Playgroud)

测试:

import React from 'react';
import Square from '../square';
import {create} from 'react-test-renderer';

describe('Square Simple Snapshot Test', () => {
    test('Testing square', () => {
        let tree = create(<Square />);
        expect(tree.toJSON()).toMatchSnapshot();
    })
})

describe('Square className is affected by isWinningSquare prop', () => {
    test('props.isWinningSquare is false, className should be "square"', () =>{
        let tree = create(<Square isWinningSquare={false} />);

        expect(tree.root.findByType('button').props.className).toEqual('square');
    }),
    test('props.isWinningSquare is true, className should be "square winning-square"', () =>{
        let tree = create(<Square isWinningSquare={true} />);

        expect(tree.root.findByType('button').props.className).toEqual('square winning-square');
    })

})
Run Code Online (Sandbox Code Playgroud)

表示为“未覆盖”的行是

onClick={() => props.onClick()}
Run Code Online (Sandbox Code Playgroud)

测试这条线的最佳方法是什么?有什么建议吗?

Jam*_*mes 7

你会使用一个模拟功能

test('props.onClick is called when button is clicked', () =>{
  const fn = jest.fn();
  let tree = create(<Square onClick={fn} />);
  // Simulate button click
  const button = tree.root.findByType('button'):
  button.props.onClick()
  // Verify callback is invoked
  expect(fn.mock.calls.length).toBe(1);
});
Run Code Online (Sandbox Code Playgroud)

此外,对于它的价值,在您的组件中,您可以将onClick处理程序直接分配给道具,即

<button
  className={className}
  onClick={props.onClick}
>
Run Code Online (Sandbox Code Playgroud)