我有以下无状态组件:
import React from 'react';
const Input = ({ name, onChange, type }) => (
<input
name={name}
onChange={onChange}
type={type} />
);
export default Input
像这样的util函数:
export const getValue = e => ({
name: e.target.getAttribute('name'),
value: e.target.value
})
和我的测试一样:
it('should call the onChange for the input element', () => {
const event = {target: {name: "pollName", value: "spam"}};
const input = shallow(<Input onChange={getValue} />)
input.simulate('change', event)
})
我从测试中得到的错误是:
TypeError: e.target.getAttribute is not a function
我没想到通过传递模拟事件
来获得此错误答案 0 :(得分:5)
simulate
函数的事件对象没有target.getAttribute
函数。您只需将其添加到那里:
const attrs = {name: "pollName", value: "spam"}
const event = {target: { getAttribute: name => attrs[name], ...attrs }};