I'm using React Context API to create a game.
In one of my components (GameStatus) I pull in some methods from the provider:
const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;
And in the component I invoke these three methods onClick of the start game button, which in turn sets the state back in the provider.
GameStatus Component
import React from 'react';
import { MyContext } from './Provider';
const GameStatus = ({ gameStart, gameEnd, score, total, getPlayers }: { gameStart: boolean, gameEnd: boolean, getPlayers: () => void, score: number, total: number }) => {
const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;
return (
<>
{!gameStart && (
<button onClick={() => {
getPlayers();
setScore(0);
setGameStart(true);
setGameEnd(false);
}}>
Start game
</button>
)}
{gameEnd && (
<p>Game end - You scored {score} out {total}</p>
)}
</>
)
}
export default GameStatus;
Then in my test file below I want to test that when the start game button is clicked the game is started (check the DOM has removed the button and is now showing the game).
But I'm not sure how to pull in the methods in to the test file as I get:
Result: TypeError: setScore is not a function
I tried just copying:
const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;
But then I get an invalid hook call as I can't use React hooks inside the test.
Any ideas? Or a better approach to testing this? Thanks
GameStatus Test
import React from 'react';
import { shallow } from 'enzyme';
import { MyContext } from '../components/Provider';
import GameStatus from '../components/GameStatus';
test('should start the game', () => {
const getPlayers = jest.fn();
const uut = shallow(
<MyContext.Provider>
<GameStatus
getPlayers={getPlayers}
/>
</MyContext.Provider>
).dive().find('button');
uut.simulate('click');
console.log(uut.debug());
});
I'm not sure if this helps but since your first approach was to use hooks inside your test you could try to use a library for rendering hooks. I'm not familiar with enzyme but I used React Hooks Testing Library in order to render my hooks inside my tests. You can use it like that:
let testYourHook= renderHook(yourHook);
testYourHook value is not dynamic, so you have to get the value everytime with:
testYourHook.result.current