JOH*_*ANO 8 testing unit-testing reactjs material-ui
我需要用酶模拟一个 onChange 事件来更新一个不工作的状态组件,我共享组件的代码以便得到帮助。
成分:
import React, { useState } from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
];
const Counter = () => {
const [value, setValue] = useState({ title: 'The Godfather', year: 1972 });
const handleAutocomplete = (e, item) => {
setValue(item);
}
return (
<>
{value && (
<p id="option">{value.title}</p>
)}
<Autocomplete
id="combo-box-demo"
name="tags"
debug
options={top100Films}
getOptionLabel={option => option.title}
onChange={handleAutocomplete}
style={{ width: 300 }}
renderInput={params => <TextField {...params} label="Combo box" variant="outlined" />}
/>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
测试组件。

import React from 'react';
import { mount } from 'enzyme';
import Counter from '../components/Counter';
describe('<Counter />', () => {
it('shoult update component', () => {
const wrapper = mount(<Counter />);
const autocomplete = wrapper.find('input');
console.log(autocomplete.debug());
autocomplete.simulate('change', { target: { value: 'The Shawshank Redemption' }});
wrapper.update();
expect(wrapper.find('p').text()).toEqual('The Shawshank Redemption');
});
});
Run Code Online (Sandbox Code Playgroud)
eps*_*lon -2
我无法帮助你,enzyme因为我不再使用它。部分原因是它在模拟事件方面不如其他库那么强大。
我个人只使用@testing-library/react这也是 Material-UI 正在使用的。然后你可以写
const { getByRole } = render(<Counter />);
const autocomplete = getByRole('textbox');
fireEvent.change(autocomplete, { target: { value: 'The Shawshank Redemption' } });
expect(autocomplete.value).to.equal('The Shawshank Redemption');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1372 次 |
| 最近记录: |