Last active
December 31, 2023 15:04
-
-
Save RomainBitard/60c39e6d928b21be37dfe215b9dabf76 to your computer and use it in GitHub Desktop.
Dependency injection using React Context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function getWordsSoundingLike(word: string): Promise<{word: string}[]> { | |
return await fetch(`https://api.datamuse.com/words?sl=${word}`) | |
.then(response => response.json()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// taken from https://www.youtube.com/watch?v=MSpDAuDPqNw | |
import OtherPage from "./OtherPage"; | |
import {fireEvent, render, screen, waitFor} from "@testing-library/react"; | |
import {DataMuseApiContext} from "./SomeLayout"; | |
describe('the page', () => { | |
it('should do stuff', async () => { | |
const logSpy = jest.spyOn(console, 'log') // never do that :p | |
render(<DataMuseApiContext.Provider value={{ | |
async getWordsSoundingLike(word: string) { | |
console.log('hello'); | |
return [{word: 'hello'}]; | |
} | |
}}><OtherPage/> | |
</DataMuseApiContext.Provider> | |
); | |
const button = screen.getByRole('button') | |
fireEvent.click(button) | |
await waitFor(() => { | |
expect(logSpy).toHaveBeenCalledWith('hello'); | |
const element = screen.getByText(/hello/i); | |
expect(element).toBeInTheDocument(); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import {useDataMuseApiContext} from "./SomeLayout"; | |
import {useState} from "react"; | |
export default function OtherPage() { | |
const dataMuseApi = useDataMuseApiContext(); | |
const [answer, setAnswer] = useState<string>(""); | |
if (!dataMuseApi) return null; | |
return <div> | |
<button onClick={ | |
async _event => { | |
const words = await dataMuseApi.getWordsSoundingLike("dog") | |
setAnswer(words[0].word) | |
console.log(words) | |
}}>Click me | |
</button> | |
{answer !== "" && <div> {answer} </div>} | |
</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment