简体   繁体   English

如何测试一个用玩笑来更新组件状态的函数

[英]How to test a function that updates state in a component with jest

Here is a snippet of my application 这是我的应用程序的片段

constructor(props) {
    super(props);
    this.state = {
      searchText:""
    };
  }

  handleSelectionInput = (e) => {
    this.setState({searchText:e.target.value});

  }

How do i test the handleSelectionInput. 我如何测试handleSelectionInput。

You can do that using enzyme. 您可以使用酶做到这一点。 check below example where i did test onchange event 检查以下示例,我在其中测试了onchange事件

import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { shallow, configure } from 'enzyme';
import Input from './Input';

configure({ adapter: new Adapter() });

test('Date with default date value handle click', () => {
  const component = shallow(
    <Input
      name="input"
      id="input"
      error
      pattern=".*"
      transformValue={value => value}
    />
  );
  expect(component.state().value).toEqual('');
  component.find('#input').simulate('change', { target: { name: 'input', value: '02' } });
  expect(component.state().value).toEqual('02');
  component.find('#input').simulate('blur', { target: { name: 'input', value: '02' } });
  expect(component.state().value).toEqual('02');
});

Hope this helps you. 希望这对您有所帮助。

I found the solution to my problem, the issue was not to simulate but rather work with the instance of the wrapper as seen below 我找到了解决问题的方法,问题不是模拟,而是使用包装器实例,如下所示

it("Test handleSelectionInput", () => {
expect(wrapper.state('searchText')).toBe("");
instance.handleSelectionInput({ target: { name: 'input', value: '02' } });
expect(wrapper.state('searchText')).toBe("02");

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Jest 的函数组件中测试回调函数 - How to test callback function in function component in Jest 如何在React TDD中使用Jest和Enzyme测试功能是否更改了组件的状态 - How to test if state of a component is changed by the function using jest and Enzyme in React TDD React&Jest,如何测试更改状态和检查另一个组件 - React & Jest, how to test changing state and checking for another component 如何在 React with Jest(无酶)中测试功能组件的 state - How to test the state of a functional component in React with Jest (No Enzyme) 使用Jest测试React Component函数 - Test a React Component function with Jest Jest / React - 如何在 function 中测试 useState state 更新的结果 - Jest / React - How to test the results of useState state update in a function 如何测试更改组件状态的函数? - How to test a function that changes the state of my component? ReactJS / Jest:如何测试/模拟传递给组件的函数 - ReactJS/Jest: How to test/mock a function, which is passed to component 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 如何测试箭头 function 用玩笑调用反应组件? - How to test arrow function calling in react component with jest?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM