我正在尝试执行一个酶/ mocha / chai测试来模拟在一个materialUI Checkbox标签中将checked的状态从true更改为false,该标签由redux-form字段包装并呈现。我能够模拟嵌套在Field标签内的本机组件(复选框等)的点击,但是在嵌套时无法模拟材质UI标签上的点击。我可以访问Checkbox标签上的其他属性,但无法模拟事件。
UserForm.jsx
renderCheckbox(props) {
return (
<Checkbox
label={props.label}
value={props.input.value}
// working code in the app:
onChange={ event => {
this.props.actions.toggleSuperAdmin(props.input.value)}}
// test code, not able to simulate even this click in Enzyme,
// tried to break function down into simplest event I could think of,
// and still not functioning in the test:
onCheck={() => console.log("onClick in UserForm.jsx")}
{...props.input}
/>
)
}
在我的渲染函数内部,有一段调用renderCheckbox
的代码块 UserForm.jsx
render() {
return (
<Paper zDepth={0} rounded={false}>
<form id='user-form' onSubmit=
{this.props.handleSubmit(this.handleUserSubmit.bind(this))}>
<Field name='is_super_admin'
component={this.renderCheckbox}
label='Work Institute Employee / Super Admin'/>
</form>
</Paper>
这是我的测试 - 我甚至不担心期望,我只是想尝试在UserForm.jsx中触发的click事件登出我的控制台。但是我包含了几行已注释掉的代码,所以你可以看到我试图用它去的地方最终我可以在Checkbox中嵌入的Click事件中嵌入字段来注销。我不确定问题是否与酶,还原形式或材料UI有关,但两者之间的相互作用不允许我模拟酶中的事件。
import ConnectedUserForm, { UserForm } from '../../../www/components/UserForm'
import { expect, shallow, render, React, sinon, mount } from '../../_utils'
import jwt from 'jsonwebtoken'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import { Field } from 'redux-form/immutable'
import Checkbox from 'material-ui/Checkbox';
import Paper from 'material-ui/Paper'
import { reducer as formReducer } from 'redux-form'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import jsdom from 'jsdom'
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.window = document.defaultView
it('toggleSuperAdmin function should fire when checkbox is checked', () => {
props.user.is_super_admin = 1
let store = createStore(combineReducers({ form: formReducer }))
const userForm = mount(
<Provider store={store}>
<ConnectedUserForm {...props} />
</Provider>, options)
const checkB = userForm.find(Checkbox)
checkB.simulate('check')
// console.log("checkB1", checkB.getNodes()[0].props);
// checkB.simulate('change', {target: { isInputChecked: true }})
// console.log("checkB2", checkB.getNodes()[0].props);
// expect(props.actions.toggleSuperAdmin.calledOnce).to.be.true
})
谢谢!
答案 0 :(得分:2)
我遇到了同样的问题并在此处找到答案:https://github.com/callemall/material-ui/blob/master/src/Checkbox/Checkbox.spec.js
const input = wrapper.find('input');
input.node.checked = !input.node.checked;
input.simulate('change');