Last active
April 6, 2026 11:30
-
-
Save cblanquera/2a0c5b0c507dc5f155467477b31208cb to your computer and use it in GitHub Desktop.
React Test Tagging - Basic Logic
This file contains hidden or 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 default AnyComponent(props: AnyComponentProps) { | |
| const tagger = useTestTagger(); | |
| return ( | |
| <div data-id={tagger('search-input')}> | |
| Anything | |
| </div> | |
| ); | |
| }; |
This file contains hidden or 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 function App() { | |
| return ( | |
| {/* Add other providers here... */} | |
| <TestProvider> | |
| {children} | |
| </TestProvider> | |
| ); | |
| }; |
This file contains hidden or 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
| //modules | |
| import type { ReactNode } from 'react'; | |
| import { createContext } from 'react'; | |
| export type TestContextProps = { | |
| name: string, | |
| prefix: stirng | |
| }; | |
| export type TestProviderProps = { | |
| name?: string, | |
| prefix?: stirng, | |
| children: ReactNode | |
| }; | |
| export const TestContext = createContext<TestContextProps>({ | |
| name: 'data-id', | |
| prefix: 'action' | |
| }); | |
| // (this is what to put in app.tsx) | |
| export function TestProvider(props: TestProviderProps) { | |
| const { children, name = 'data-id', prefix = 'action' } = props; | |
| return ( | |
| <TestContext.Provider value={{ name, prefix }}> | |
| {children} | |
| </TestContext.Provider> | |
| ); | |
| }; | |
| export function useTesting() { | |
| return useContext(TestContext); | |
| }; | |
| export function useTestTagger() { | |
| const context = useTesting(); | |
| return (tag: string) => `${context.prefix}-${tag}`; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment