reactjs - 无法使用 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>
解决方案
使用WrappedComponent访问 HOC 包装的 html 和dive()
嵌套的 html。它应该可以工作
shallow(<App.WrappedComponent handleChange={handleChange} />).dive();
您可以访问标签,例如wrapper.find('WithStyles(Taps)')
推荐阅读
- android - Expo Push Notifications 在生产中不起作用
- mongodb - 在 mongoDB 中按 _id 搜索是否更有效?
- javascript - 如何在 d3.format 中添加任何字符串作为数字的后缀?
- r - 从命令提示符执行 R 脚本时出错
- mongodb - 在 MongoDB 5.0.1 中创建时序集合会引发错误时序集合未启用
- laravel-7 - 在 Finder.php 第 590 行:“”目录不退出。在生产中运行 php artisan optimize:clear 后
- javascript - 属性或方法“foo”未在实例上定义,但在渲染期间被引用
- android-studio - Android Studio Git 合并显示空白屏幕,冲突无法解决
- c# - C#在Datatable中添加动态列和行
- c# - 有没有办法根据收到的对象的类型来确定资产的范围?