测试反应功能组件上的酶中的点击事件未通过

时间:2020-06-04 19:38:51

标签: javascript reactjs unit-testing jestjs enzyme

我正在尝试为单击按钮时编写一个测试,该测试将调用handleClick函数,但在测试中的断言中我一直收到错误。 这是React组件:

function Profile() {

    const [name, setName] = useState({
        firstName: '',
        lastName: ''
    });
    const [names, setNames] = useState([]);

    const handleClick = (e) => {
        e.preventDefault();
        names.push(name);
    }

    return ( 
       <form >
        <input 
          type = "text"
          value = {name.firstName}
          onChange = {
            e => setName({
                ...name,
                firstName: e.target.value
            })
        }/> 
        <input 
          type = "text"
          value = {name.lastName}
          onChange = {
            e => setName({
                ...name,
                lastName: e.target.value
            })
        }/> 
        <button onClick = {handleClick} > Add Name < /button> </form>
    )
}
export default Profile

这是测试:

it('test 1 - call handleClick spy', () => {
  const handleClick = sinon.spy();
  let wrapper = shallow(<Profile handleClick={handleClick}/>);  
  wrapper.find('button').simulate('click',{preventDefault:()=>{}});
  expect(handleClick.calledOnce).toBe(true); 
  }); 

1 个答案:

答案 0 :(得分:0)

click事件不会触发您传入的模拟BOOL CALLBACK DialogProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch (iMsg) { case WM_INITDIALOG : SetDlgItemText ( hDlg, ID_BUTTON, "Button Text" ); return TRUE ; } return FALSE ; } 方法,而是触发在组件内部定义的handleClick方法。这就是为什么不调用模拟的handleClick方法的原因。

要确定是否正在调用组件内部的handleClick方法,可以使用诸如handleClick之类的间接方法来确定是否正在调用preventDefault函数。

例如

preventDefault

index.jsx

import React, { useState } from 'react'; function Profile() { const [name, setName] = useState({ firstName: '', lastName: '', }); const [names, setNames] = useState([]); const handleClick = (e) => { e.preventDefault(); names.push(name); }; return ( <form> <input type="text" value={name.firstName} onChange={(e) => setName({ ...name, firstName: e.target.value, }) } /> <input type="text" value={name.lastName} onChange={(e) => setName({ ...name, lastName: e.target.value, }) } /> <button onClick={handleClick}> Add Name </button>{' '} </form> ); } export default Profile;

index.test.jsx

单元测试结果:

import React from 'react';
import Profile from '.';
import { shallow } from 'enzyme';

describe('62202833', () => {
  it('should pass', () => {
    const wrapper = shallow(<Profile></Profile>);
    const mEvent = { preventDefault: jest.fn() };
    wrapper.find('button').simulate('click', mEvent);
    expect(mEvent.preventDefault).toBeCalledTimes(1);
  });
});