Enzyme 是否仅适用于较低级别的组件?

Does Enzyme only work with lower level components?

我正在为 React/Redux/Grommet 应用编写一些单元测试。为了测试,我使用 Jest/Enzyme/Chai/Sinon.

我有以下组件:

import React from 'react'
import FormField from 'grommet/components/FormField'
import Box from 'grommet/components/Box'
import Label from 'grommet/components/Label'
import TextInput from 'grommet/components/TextInput'

const CustomTextInput = ({label, value, onChange}) =>
    <FormField label={<Label size='small'>{label}</Label>}>
        <Box pad={{'horizontal': 'medium'}}>
            <TextInput placeholder='Please Enter' value={value}
                onDOMChange={event => onChange(event.target.value)}
            />
        </Box>
    </FormField>

export default CustomTextInput

并且以下测试失败:

import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { expect } from 'chai'
var sinon = require('sinon');
import CustomTextInput from '../src/customInputs/CustomTextInput'
import TextInput from 'grommet/components/TextInput'
import Box from 'grommet/components/Box'
import FormField from 'grommet/components/FormField'


describe('<CustomTextInput />', () => {
    it('input changes', () => {
        let onChange = sinon.spy();
        const wrapper = shallow(<CustomTextInput label={'test'} value={'test'} onChange={onChange} />)
        wrapper.find(TextInput).simulate('keypress', {which: 'a'})
        expect(onChange.called).to.equal(true)
    })
})

出现此错误:

AssertionError: expected false to equal true

我尝试用几种不同的方式模拟 onChange 函数,主要是从 here and here 中汲取灵感。即

wrapper.find(TextInput).value = 'test'
wrapper.find(TextInput).simulate('change', {target: {value: 'test'}})
wrapper.find(TextInput).first().simulate('change', {target: {value: 'test'}})

我开始怀疑酶的 simulate 方法是否在与更高级别的库组件(如索环中的组件)交互时遇到问题,或者是否需要将其直接应用于较低级别的 <input> 标签。有没有人经历过这种事情?

grommet TextInput 只是标准输入表单字段的包装器,所以试试这个:

wrapper.find('input').simulate('change', {target: { value: 'a'}});

希望我的回答能对您有所帮助!