【发布时间】:2021-09-10 19:29:17
【问题描述】:
我是 testing-library 和 jest 的新手,我正在尝试测试组件内部的一个函数,该函数会更改输入的值。该组件是一个表单,另一个组件是它的输入。
export const Form = () => {
const [name, setName] = useState("");
const handleOnSubmit = e => {
e.preventDefault();
const form = e.target;
};
const inputChange = (param) => (e) => {
const inputValue = e.target.value;
setName(inputValue);
};
return (
<form className="form" onSubmit={handleOnSubmit}>
<InputGroup text="name" type="text" value={name} functionality={inputChange("name")}/>
<Button type="submit" disabled={name === undefined}/>
</form>
);
};
export default Form;
InputGroup 组件如下所示
export const InputGroup = ({type, id, value, required, functionality, text}) => {
return (
<label>{text}</label>
<input className="input" type={type} id={id} name={id} value={value}
required={required} onChange={functionality}
/>
);
};
我已经尝试过类似的方法,但我不太确定如何测试直接在组件 Form 上的函数以及它正在传递给组件 InputGroup。
describe("Form", () => {
let value;
let component;
const handleSubmit = jest.fn();
const handleChange = ev => {
ev.preventDefault();
value = ev.currentTarget.value;
}
beforeEach(() => {
component = render(
<Form onSubmit={handleSubmit} functionality={handleChange} />
);
});
it("check error name is triggered", () => {
const input = component.getByText("name");
fireEvent.change(input, {target: {value: "aaa"}});
});
});
我收到一条错误消息,上面写着“给定元素没有值设置器”,那么如何将 inputChange 函数传递给 InputGroup 组件?
【问题讨论】:
-
我不明白你有没有在
Form或InputGroup中定义的道具functionality?如果是这样,请同时发布代码。 -
我刚刚添加了输入组件@windmaomao。谢谢你的回答!
标签: reactjs testing jestjs testing-library