Skip to content

Instantly share code, notes, and snippets.

@RomainBitard
Last active December 31, 2023 15:04
Show Gist options
  • Save RomainBitard/60c39e6d928b21be37dfe215b9dabf76 to your computer and use it in GitHub Desktop.
Save RomainBitard/60c39e6d928b21be37dfe215b9dabf76 to your computer and use it in GitHub Desktop.
Dependency injection using React Context
export async function getWordsSoundingLike(word: string): Promise<{word: string}[]> {
return await fetch(`https://api.datamuse.com/words?sl=${word}`)
.then(response => response.json());
}
// 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();
});
});
});
"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