簡體   English   中英

如何使用Jest測試React組件的onClick行?

[英]How can I test an onClick line of a React component using Jest?

我正在學習React,目前正在嘗試開玩笑/測試。 我正在一個小項目上開始測試,我想獲得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()}

測試這條線的最佳方法是什么? 有什么建議嗎?

您將使用模擬功能

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處理程序分配給prop,即

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

只需定位元素並調用其處理程序:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM