Skip to content

Commit

Permalink
Add useState example
Browse files Browse the repository at this point in the history
  • Loading branch information
nickovchinnikov committed Sep 23, 2021
1 parent b0893db commit 212a7ef
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
28 changes: 28 additions & 0 deletions examples/useStateAndUseEffect/ClickCounter.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';

import { ClickCounter } from './ClickCounter';

describe('Test ClickCounter', () => {
it('should inc/dec counter when buttons inc/dec clicked', () => {
render(<ClickCounter />);

const counter = screen.getByRole('heading');
const increaseBtn = screen.getByRole('button', { name: 'Increase' });
const decreaseBtn = screen.getByRole('button', { name: 'Decrease' });

expect(counter.textContent).toBe('Counter: 0');

fireEvent.click(increaseBtn);
expect(counter.textContent).toBe('Counter: 1');

fireEvent.click(increaseBtn);
expect(counter.textContent).toBe('Counter: 2');

fireEvent.click(decreaseBtn);
expect(counter.textContent).toBe('Counter: 1');

fireEvent.click(decreaseBtn);
expect(counter.textContent).toBe('Counter: 0');
});
});
17 changes: 17 additions & 0 deletions examples/useStateAndUseEffect/ClickCounter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React, { FC, useState } from 'react';

interface Props {
defaultCount?: number;
}

export const ClickCounter: FC<Props> = ({ defaultCount = 0 }) => {
const [count, setCount] = useState(defaultCount);

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)}>Decrease</button>
</div>
);
};

0 comments on commit 212a7ef

Please sign in to comment.