我对Jest和测试来说相对较新。我有一个带有文本输入元素的组件:
这是我的代码段
<TextInput
testID="messageText"
ref={inputRef}
value={title}
onChangeText={(text) => {
setTitle(text)
}}
/>
每次我遇到错误
方法“模拟”旨在在1个节点上运行。而是找到2个。
这是我的代码-
const navigation = jest.fn()
const onChange = jest.fn();
const props = {
navigation: {
state: {
params: {
postType: 'text'
}
}
},
}
let wrapper
const event = {
target: {
value: 'This is just for test'
}
}
it('renders', () => {
wrapper = shallow(<NewFeedComponent {...props} />)
wrapper.find('Text').simulate('change', event)
expect(onChange).toHaveBeenCalledWith('This is just for test');
})
})
答案 0 :(得分:0)
我创建了一个沙箱,以便您可以了解更多上下文。只需通过此沙箱即可(不要忘记运行测试运行程序以查看实际的测试工作):
代码:
App.js
import React, { useState } from "react";
import "./styles.css";
export default function App(props) {
const [value, setValue] = useState("");
return (
<input
type={props.type}
value={value}
name="email"
className="basic-input"
placeholder={props.placeholder}
onChange={(e) => setValue(e.target.value)}
/>
);
}
App.test.js
import React from "react";
import ReactDOM from "react-dom";
import Adapter from "enzyme-adapter-react-16";
import { mount, shallow, configure } from "enzyme";
import App from "./App";
configure({ adapter: new Adapter() });
describe("basic input component", () => {
it("should renders without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
it("should render a placeholder", () => {
const placeholder_text = "type anything here";
const wrapper = shallow(<App placeholder={placeholder_text} />);
expect(wrapper.prop("placeholder")).toEqual(placeholder_text);
});
it("should render a correct type", () => {
const type = "password";
const wrapper = shallow(<App type={type} />);
expect(wrapper.prop("type")).toEqual(type);
});
it("should change the state after change the input value", () => {
const newValue = "testing component";
const wrapper = mount(<App value="" type="text" />);
// const input = wrapper.find('input[type="text"]');
wrapper
.find('input[name="email"]')
.simulate("change", { target: { value: newValue } });
expect(wrapper.find('input[name="email"]').prop("value")).toEqual(newValue);
});
});
以下是演示:https://codesandbox.io/s/react-jest-enzyme-jn3ld?file=/src/App.js:0-360