首页 > 解决方案 > 无法使用 Material UI HOC 模拟 React 组件上的更改事件

问题描述

我无法模拟和观察 Material UI HOC 上的点击。出于某种原因,传递 onChange 属性似乎不会导致调用关联的 handleChange 事件处理程序。

我的代码如下:

import React from 'react';
import { mount } from 'enzyme';
import App from '../App/App';
import Tabs from '@material-ui/core/Tabs';
import { createShallow } from '@material-ui/core/test-utils';
import { createMount } from '@material-ui/core/test-utils';
import { expect } from 'chai';
import { stub } from 'sinon';


describe('App', () => {
  let wrapper;
  let shallow;
  beforeEach(() => {
    wrapper = mount(<App />);
    shallow = createShallow();
    mount2 = createMount();
  });

  afterEach(() => {
    wrapper.unmount();
  });

  it('should call onChange prop with input value 1', () => {

    const handleChange = stub();
    let wrapper2 = shallow(<App handleChange={handleChange} />);
    wrapper2.find(Tabs).prop('onChange')({
      target: { value: '1' } 
    });
    expect(wrapper2.html()).to.exist;
    console.log(wrapper2.debug())
    expect(handleChange.callCount).to.be.equal(1);

  });

});

观察我的测试输出时,我收到以下信息:

 FAIL  src/components/__tests__/App.spec.js
  ● App › should call onChange prop with input value 1

    AssertionError: expected 0 to equal 1

      at Object.it (src/components/__tests__/App.spec.js:32:53)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

  App
    ✕ should call onChange prop with input value 1 (84ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.411s
Ran all test suites related to changed files.

  console.log src/components/__tests__/App.spec.js:31
    <div>
      <WithStyles(Paper) square={true}>
        <WithStyles(Tabs) className="theTabsClassname" value={[undefined]} indicatorColor="primary" textColor="primary" onChange={[Function: bound ]}>
          <WithStyles(Tab) className="tab1" label="Sales Analysis" icon={{...}} />
          <WithStyles(Tab) className="tab2" label="AOV Analysis" icon={{...}} />
          <WithStyles(Tab) className="tab3" label="Access Analysis" icon={{...}} />
        </WithStyles(Tabs)>
        <WithStyles(DatePickers) onDateSelect={[Function: bound setCurrentDate]} />
      </WithStyles(Paper)>
    </div>

标签: reactjsmaterial-uisinonhigher-order-components

解决方案


使用WrappedComponent访问 HOC 包装的 html 和dive()嵌套的 html。它应该可以工作

 shallow(<App.WrappedComponent handleChange={handleChange} />).dive();

您可以访问标签,例如wrapper.find('WithStyles(Taps)')


推荐阅读