Ad
How To Test Component Which Render Children Elements Inside?
I have following component:
export default function Button({ className, children, ...otherProps }) {
return (
<button className={'button} {...otherProps}>
{children}
</button>
);
}
and in parent component I passed such props and tag inside:
<Button className={test-button} onClick={this.removeItems} >
<i className="fa fa-trash-alt" /> Remove all items
</Button>
I cannot understand how to properly unit test such components. For example I want to test onClick
function to have been called when I click on the component.
I wrote such a test:
const buttonFunc = jest.fn();
const props = {
children: {
className: "test",
onClick: buttonFunc,
}
};
let wrapper;
beforeEach(() => {
wrapper = shallow(<Button {...props} />);
});
test('click on switch button', () => {
wrapper.simulate('click');
expect(buttonFunc).toHaveBeenCalledTimes(1);
console.log(wrapper.debug())
});
but I have an error
Expected mock function to have been called one time, but it was called zero times.
Ad
Answer
You are passing props wrongly. You don't need to pass children as named property. you can add that in your shallow method. onClick and className are props, should not be inside children.
const props = {
className: "test",
onClick: buttonFunc,
};
wrapper = shallow(<Button {...props}> Button Text </Button>);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad