:) A wiec ucze sie robienia testow w Jest, i mam dwa components do ktorych te testy chcialabym zrobic.
pierwszy component:
import React, {useState} from 'react';
const steps = [{ name: 'Hjem' }, { name: 'Game' }, { name: 'End' }]
const Stepper = () => {
const [step, setStep] = useState(0)
return (
<>
{step + 1 < steps.length ? (
<button type="button" onClick={() => setStep(step + 1)}>
{steps[step + 1].name}
</button>
) : null}
</>
)
}
export default Stepper;
I chcialabym to niego zrobic serie testow. Jako ze dopiero ucze sie tych spraw i doswiadczenia mam niewiele, nie jestem w stanie napisac testow. Cos tam probuje, ale gladko to nie idzie.
import React from 'react';
import {render} from '@testing-library/react';
import Stepper from '../components/Stepper';
describe('Stepper component', () => {
it('should render button', () => {
render(<Stepper/>)
})
it('should have correct text content on button', () => {
render(<Stepper/>)
const p = document.querySelector('button')
expect(p).toHaveTextContent()
})
it('should update step-count and button content on click', async () => {
})
it('should remove button when step count is higher than amount of steps', async () => {
})
})
Taki oto mam test. Wiem ze should update step count on button content on click trzeba przetestowac poprzez mock functions, ale nie wiem do konca jak.
A to drugi component + test::
const ColorPicker = ({ colors, selectedColor, handleSelectedColor }) => {
return (
<ul className="colorPicker">
{colors.map((color) => (
<li key={color} data-testid="color">
<button
style={{
backgroundColor: color,
opacity: selectedColor ? (selectedColor === color ? 1 : 0.2) : 1,
}}
disabled={selectedColor && selectedColor !== color}
onClick={() => handleSelectedColor(color)}
></button>
</li>
))}
</ul>
)
}
export default ColorPicker;
describe('ColorPicker', () => {
afterEach(() => {
jest.clearAllMocks()
})
it('should render a list of all colors passed to it', () => {
})
it('should have disabled button if color does not match', () => {
})
it('should have one active button if color match', () => {
})
it('should have called onClick on button', async () => {
})
it('should not have called onClick on disabled button', async () => {
})
it('should updated selectedColor and active buttons on click', async () => {
})
})
Dokumentacje czytalam, ale jako ze mam malo doswiadczenia wydaje sie to nieintuitywne, a chcialabym wiedziec jak takie testy robic i latwiej sobie jakies pojecie o tym wyrobic na podstawie przykladow. Ktos mialby czas i chec pomoc mi z tym?