I'm relatively new to Jest and testing in general. I have a component with a text input element:
Here is my code snippet
<TextInput
testID="messageText"
ref={inputRef}
value={title}
onChangeText={(text) => {
setTitle(text)
}}
/>
Every time I am getting the error
Method “simulate” is meant to be run on 1 node. 2 found instead.
Here is my code --
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');
})
})
I created one sandbox so that you can understand more context. Just go through this sandbox(dont forget to run test runner to see actually test works):
code:
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);
});
});
Here is the demo: https://codesandbox.io/s/react-jest-enzyme-jn3ld?file=/src/App.js:0-360
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.