--- id: 5a24c314108439a4d4036177 title: Write a Simple Counter challengeType: 6 isRequired: false videoUrl: '' localeTitle: Написать простой счетчик --- ## Description
Вы можете создать более сложный компонент, поддерживающий состояние, путем объединения концепций, охваченных до сих пор. К ним относятся инициализация state , методы записи, которые устанавливают state , и назначение обработчиков кликов для запуска этих методов.
## Instructions
Компонент Counter отслеживает значение count в state . Есть две кнопки, которые вызывают методы increment() и decrement() . Запишите эти методы, чтобы значение счетчика увеличивалось или уменьшалось на 1 при нажатии соответствующей кнопки. Кроме того, создайте метод reset() чтобы при нажатии кнопки сброса счетчик был установлен на 0. Примечание. Убедитесь, что вы не изменяете classNames кнопок. Кроме того, не забудьте добавить необходимые привязки для вновь созданных методов в конструкторе.
## Tests
```yml tests: - text: 'Counter должен возвращать элемент div который содержит три кнопки с текстовым содержимым в этом порядке Increment! , Decrement! , Reset .' testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Counter)); return (mockedComponent.find(".inc").text() === "Increment!" && mockedComponent.find(".dec").text() === "Decrement!" && mockedComponent.find(".reset").text() === "Reset"); })(), "Counter should return a div element which contains three buttons with text content in this order Increment!, Decrement!, Reset.");' - text: Состояние Counter должно быть инициализировано с использованием свойства count равного 0 . testString: 'assert.strictEqual(Enzyme.mount(React.createElement(Counter)).state("count"), 0, "The state of Counter should initialize with a count property set to 0.");' - text: Нажатие кнопки инкремента должно увеличивать счет на 1 . testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const first = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state("count")); }; const second = () => { mockedComponent.find(".inc").simulate("click"); return waitForIt(() => mockedComponent.state("count")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1, "Clicking the increment button should increment the count by 1."); }; ' - text: '' testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const first = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state("count")); }; const second = () => { mockedComponent.find(".dec").simulate("click"); return waitForIt(() => mockedComponent.state("count")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === -1, "Clicking the decrement button should decrement the count by 1."); }; ' - text: Нажатие кнопки сброса должно сбрасывать счетчик на 0 . testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const init = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state("count")); }; const increment = () => { mockedComponent.find(".inc").simulate("click"); mockedComponent.find(".inc").simulate("click"); return waitForIt(() => mockedComponent.state("count")); }; const decrement = () => { mockedComponent.find(".dec").simulate("click"); return waitForIt(() => mockedComponent.state("count")); }; const reset = () => { mockedComponent.find(".reset").simulate("click"); return waitForIt(() => mockedComponent.state("count")); }; const firstValue = await init(); const secondValue = await increment(); const thirdValue = await decrement(); const fourthValue = await reset(); assert(firstValue === 0 && secondValue === 2 && thirdValue === 1 && fourthValue === 0, "Clicking the reset button should reset the count to 0."); }; ' ```
## Challenge Seed
```jsx class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; // change code below this line // change code above this line } // change code below this line // change code above this line render() { return (

Current Count: {this.state.count}

); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```