如何使用Jest测试React组件中onClick事件的代码行?

3

我正在学习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

测试:

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');
    })

})

“未覆盖”的那条线是

onClick={() => props.onClick()}

如何测试这条线路?有什么建议吗?

2个回答

8
你会使用一个模拟函数
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);
});

另外,值得一提的是,在您的组件中,您可以直接将onClick处理程序分配给属性,即:

<button
  className={className}
  onClick={props.onClick}
>

这很有帮助,谢谢。还有感谢您额外的提示! - Garrett Daniel DeMeyer

0

只需定位元素并调用其处理程序:

tree.root.findByType('button').props.onClick();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接