I'm testing a React app for the first time and I'm struggling to write tests that check if an array in a component has 2 elements on first render and on clicking a button.
The error I'm getting is TypeError: Expected container to be an Element, a Document or a DocumentFragment but got string.
Here's the component where I need to test usersCards
- it needs to have two elements on first render and every time the user clicks 'deal'.
I'm not sure how to deal with variables in components - do I mock it up in the test file? Ant help appreciated!
\\imports
export default function Home(){
const startHandSize = 2
const [starterDeck, setStarterDeck] = useState(shuffle(deckArray))
const [howManyDealt, setHowManyDealt] = useState(startHandSize)
const [total, setTotal] = useState(0)
const [ace, setAce] = useState(0)
const deal = () => {
setHowManyDealt(startHandSize)
setStarterDeck(shuffle(deckArray))
setAce(0)
}
const hit = () => !bust && setHowManyDealt(prev => prev 1)
const usersCards = starterDeck.slice(-howManyDealt)
const bust = total > 21;
useEffect(() => {
setTotal(usersCards.reduce((a, e) => a e.value, 0) ace)
}, [ace, usersCards])
return(
<div>
{
<>
<button data-testid="deal" onClick={deal}>DEAL</button>
<button data-testid="hit" disabled={bust} onClick={hit}>HIT</button>
<button disabled={bust}>STAND</button>
<Total total={total}/>
{usersCards.map(card => (
<Card data-testid="test-card" key={card.index}
card={card} setTotal={setTotal} total={total}
ace={ace} setAce={setAce}
/>
))}
</>}
</div>
)
}
Here's the test:
//Deal button test
test("on initial render, two cards are displayed", () => {
render(<Home />)
const cards = getAllByTestId('test-card')
expect(cards.length).toEqual(2)
})
CodePudding user response:
I guess something like that would work:
test("on initial render, two cards are displayed", () => {
const { getAllByTestId } = render(<Home />);
const cards = getAllByTestId('test-card');
expect(cards.length).toEqual(2);
});
test("two new cards should be displayed after clicking the button", () => {
const { getAllByTestId, getByTestId } = render(<Home />);
const dealButton = getByTestId('deal');
fireEvent.click(dealButton);
const cards = getAllByTestId('test-card');
expect(cards.length).toEqual(2);
});