【发布时间】:2020-04-02 23:54:20
【问题描述】:
我目前有一个带有onChange 方法的反应组件。
我想测试 onChange 方法,就像有人要输入或粘贴内容一样。问题是 handleChange 依赖于使用它的父组件。测试模拟的最佳方法是什么?我需要引用父组件的handleChange 方法并进行模拟吗?
CodeSandbox(我没有在这里添加测试)
https://codesandbox.io/s/react-basic-example-cwdh1?from-embed
更新当前测试:
const handleChange = jest.fn();
const initProps = {
name: "Title",
label: "Body",
type: "text",
value: "",
handleChange
};
describe("TextBox", () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<TextBox {...props} />);
});
afterEach(() => {
// resets the mocked fn after each test
handleChange.mockClear();
});
it("should call handleChange with a new value", () => {
const value = "testing input";
wrapper.find("input").simulate("change", { target: { value } });
expect(handleChange).toHaveBeenCalledWith(value);
});
});
错误:
Expected: "testing input"
Received: {"_dispatchInstances": null, "_dispatchListeners": null,
"_targetInst": ......more fields... "nativeEvent": {"target": <input … />,
"type": "change"}, "target": {"value": "testing input"}, "timeStamp":
1576040322012, "type": "change"}
我知道我收到此错误是因为该值来自表单域。有没有办法可以提取目标字段?
【问题讨论】: