Skip to content

Instantly share code, notes, and snippets.

@mzibari
Created April 19, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzibari/c4d5882a270ae428b5465ee1ea40ee23 to your computer and use it in GitHub Desktop.
Save mzibari/c4d5882a270ae428b5465ee1ea40ee23 to your computer and use it in GitHub Desktop.
testing event listeners
<<<<<<ACCORDION.JS>>>>>>
import React from 'react';
class Accordion extends React.Component {
static defaultProps = {
sections: []
}
state = {
currentSectionIndex: null
};
handelClick(index) {
/* I wrote the if statement so that if the same button is clicked twice the content will disappear */
if (this.state.currentSectionIndex === index) {
this.setState({ currentSectionIndex: null });
}
else {
this.setState({ currentSectionIndex: index });
}
}
renderSections() {
const list = this.props.sections.map((section, index) => (
<li><button key={index} onClick={() => this.handelClick(index)}>{section.title}</button>
{(this.state.currentSectionIndex === index) && (<p>{this.renderContent()}</p>)}</li>
));
return list;
}
renderContent() {
const currentSection = this.props.sections[this.state.currentSectionIndex];
return currentSection.content;
}
render() {
return (
<ul>{this.renderSections()}</ul>
);
}
}
export default Accordion;
<<<<<<ACCORDION.TEST.JS>>>>>>
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Accordion from './Accordion'
const sections = [
{
title: 'Section 1',
content: 'Section one Lorem ipsum dolor sit amet consectetur adipisicing elit.',
},
{
title: 'Section 2',
content: 'Section two Cupiditate tenetur aliquam necessitatibus id distinctio quas nihil ipsam nisi modi!',
},
{
title: 'Section 3',
content: 'Section three Animi amet cumque sint cupiditate officia ab voluptatibus libero optio et?',
},
]
describe('Accordion tests', () => {
it('renders without errors when empty', () => {
const wrapper = shallow(<Accordion />);
expect(toJson(wrapper)).toMatchSnapshot();
});
it('renders no sections as active by default', () => {
const wrapper = shallow(<Accordion sections={sections}/>);
expect(toJson(wrapper)).toMatchSnapshot();
});
it('renders selected section', () => {
const wrapper = shallow(<Accordion sections={sections}/>);
wrapper.find('button').at(1).simulate('click');
expect(toJson(wrapper)).toMatchSnapshot();
});
it('only opens one section at a time', () => {
const wrapper = shallow(<Accordion sections={sections} />);
wrapper.find('button').at(1).simulate('click');
wrapper.find('button').at(2).simulate('click');
expect(toJson(wrapper)).toMatchSnapshot();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment