Last active
November 9, 2021 17:03
-
-
Save davidmfoley/bcde10aaac3bd27677a3a939f424b405 to your computer and use it in GitHub Desktop.
Example of using react context for dependency inversion
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
import { createTodo, updateTodo, deleteTodo } from './real-todo-api-client' | |
import React from 'react' | |
// create a context where the default value is the "real" production implementation | |
export const TodoApi = useContext({ | |
getTodos, | |
createTodo, | |
updateTodo, | |
deleteTodo | |
}) | |
export const useTodos = () => { | |
// get dependencies from context | |
const api = useContext(TodoApi) | |
const [todos, setTodos] = React.useState([]) | |
useEffect(() => { | |
api.getTodos().then(setTodos) | |
}, []) | |
return { todos } | |
} |
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
import isolateHook from 'isolate-hooks' | |
import { useTodos, TodoApi } from './useTodos' | |
// jest | |
test('some test of useTodos', () => { | |
// fake api implementation | |
const fakeTodoApi = { | |
getTodos: jest.fn(), | |
createTodo: jest.fn(), | |
updateTodo: jest.fn(), | |
deleteTodo: jest.fn(), | |
} | |
const hook = isolateHook(useTodos) | |
// inject via context | |
hook.setContext(TodoApi, fakeTodoApi) | |
fakeTodoApi.getTodos.mockResolvedValue([ {id: 1, text: 'example todo'}]) | |
hook(); | |
// wait for promises to settle | |
await new Promise(setImmediate); | |
expect(hook().todos.length).toEqual(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment