问题
I am trying to test a React component using Jest and Enzyme. I want to simulate a click event on a Button component which is inside a div with a specific class name. I can't retrieve the Button node.
I have the following markup in my component
<div className="settings">
<Button
onClick={() => this.toggleSettingsModal(true)}
buttonStyle={ButtonStyle.Primary}>
Settings
</Button>
</div>
I have tried
const component = shallow(<MyComponent />);
component.find(".settings[Button]").simulate("click");
I expect to find the Button component, but I get 0
nodes.
回答1:
Try the code below
import { shallow } from 'enzyme'
import MyComponent from './MyComponent'
describe('<MyComponent />', () => {
it('simulates click events', () => {
const component = shallow(<MyComponent />);
component.find(Button).simulate("click");
});
});
EDIT Try the code below:
expect(component
.find(Button)
.closest('.settings'))
.simulate("click");
回答2:
The type of element isn't a Button
, thats the component name. It is probably a button
or input
. You can do it like this depending on what element type the node is:
const foo = shallow(<MyComponent />);
foo.find(".settings[button]").simulate("click");
To make this more specific you could always add a class to the button.
Or, per the documentation, if you'd like to you can target it by inputting the component to the test and then finding it that way:
import Bar from '../components/Foo';
const wrapper = shallow(<MyComponent />);
wrapper.find(Bar).simulate("click");
Finally, without any additional imports you can use the display name of the component like so:
const baz = shallow(<MyComponent />);
baz.find('Button').simulate("click");
来源:https://stackoverflow.com/questions/55451529/how-to-find-a-react-component-inside-an-element-with-specific-class-using-enzyme