I would like to find the button in my component and simulate a click.
I have code:
const wrapper = shallow(<MyComponent />);
console.log(wrapper.html()); // <div><button class="myButton">Save</button><button variant="light" class="myButton">Close</button></div>
console.log(wrapper.contains('button')); // false
console.log(wrapper.filter('button')); // false
I don't understand what is wrong, button exist - you can see it in wrapper.html()
Same for demo example:
const wrapper = shallow(
<div>
<button>xx</button>
</div>,
);
console.log(wrapper.html()); // <div><button>xx</button></div>
console.log(wrapper.contains('button')); // false
console.log(wrapper.filter('button')); // false
.contains(nodeOrNodes) => Boolean method accepts ReactElement|Array<ReactElement>
as its parameter, NOT a selector .
.filter(selector) => ShallowWrapper method accept a selector
as its parameter.
Returns a new wrapper with only the nodes of the current wrapper that match the provided selector.
For more unit testings, see filter
Eg
import React from 'react';
import { shallow } from 'enzyme';
describe('64240490', () => {
it('should pass', () => {
const wrapper = shallow(
<div>
<button className="foo">xx</button>
<span className="foo">foo</span>
</div>,
);
expect(wrapper.contains(<button className="foo">xx</button>)).toBeTruthy();
expect(wrapper.find('.foo').filter('button')).toHaveLength(1);
});
});
unit test result:
PASS src/stackoverflow/64240490/index.test.tsx (9.234s)
64240490
✓ should pass (11ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.209s
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.