如何单元测试状态更改来自反应钩子中的组件的回调



我正在编写单元测试,并希望测试组件的状态更改回调。

单元测试代码

import React from 'react';
import {configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NameTextField from './NameTextField';
import TextField from '@material-ui/core/TextField';
import {createShallow} from '@material-ui/core/test-utils';
import {act} from 'react-dom/test-utils';
configure({adapter: new Adapter()});
describe('<NameTextField />', () => {
  let shallow;
  beforeAll(() => {
    shallow = createShallow();
  });
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<NameTextField onStateChange={handleStateChange}/>);
  });

  const handleStateChange = updatedState => {
  };

  it('should show no error when correctly entered', () => {
    const handleStateChange = jest.fn()
    act(() => {
      wrapper.find(TextField).at(0).simulate('blur', {target: {value: 'correct name'}});
    });
    wrapper.update();
    expect(wrapper.find(TextField).at(0).props().error).toBe(
        false);
    expect(wrapper.find(TextField).at(0).props().helperText).toBe(
        null);
    expect(handleStateChange).toHaveBeenCalledWith('10')
  });
});

我这里有NameTextField组件,根据它在Textfield上的输入,我得到StateChange回调。

<NameTextField onStateChange={handleStateChange}/>

当我使用

    expect(handleStateChange).toHaveBeenCalledWith('10')

我收到错误消息,说

Error: expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
  ["10"]
But it was not called.

如何捕获组件上的状态更改回调?

我在这里发布后立即找到了答案。

简单的错误。

import React from 'react';
import {configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NameTextField from './NameTextField';
import TextField from '@material-ui/core/TextField';
import {createShallow} from '@material-ui/core/test-utils';
import {act} from 'react-dom/test-utils';
configure({adapter: new Adapter()});
describe('<NameTextField />', () => {
  let shallow;
  beforeAll(() => {
    shallow = createShallow();
  });
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<NameTextField onStateChange={handleStateChange}/>);
  });

    const handleStateChange = jest.fn();

  it('should show no error when correctly entered', () => {
    act(() => {
      wrapper.find(TextField).at(0).simulate('blur', {target: {value: 'correct name'}});
    });
    wrapper.update();
    expect(wrapper.find(TextField).at(0).props().error).toBe(
        false);
    expect(wrapper.find(TextField).at(0).props().helperText).toBe(
        null);
    expect(handleStateChange).toHaveBeenCalledWith('10')
  });
});

const handleStateChange = jest.fn((;

有重复的句柄状态更改。

相关内容

  • 没有找到相关文章

最新更新