Jest mock react context
You just render the context with your component. const addItem = jest.fn() render( <AppContext.Provider value={{ addItem }}> <MyComponent /> </AppContext.Provider> ) See Mocking context with react-testing-library
You just render the context with your component. const addItem = jest.fn() render( <AppContext.Provider value={{ addItem }}> <MyComponent /> </AppContext.Provider> ) See Mocking context with react-testing-library
Are updated to the context not propagated via the ususal rerenders? As I cannot see my logs / color changes when context changes. The updates to context values doesn’t trigger re-render for all the children of the provider, rather only components that are rendered from within the Consumer, so in your case although number component … Read more
You could use the useContext hook to achieve this. It’s quite easy to use it in the child elements of the Provider. As an example… authContext.js import { createContext } from “react”; const authContext = createContext({ authenticated: false, setAuthenticated: (auth) => {} }); export default authContext; Login.js (component consuming the Context) import React, { useContext … Read more
EDIT: With the introduction of react-hooks in v16.8.0, you can use context in functional components by making use of useContext hook const Users = () => { const contextValue = useContext(UserContext); // rest logic here } EDIT: From version 16.6.0 onwards. You can make use of context in lifecycle method using this.context like class Users … Read more
How to update context with hooks is discussed in the How to avoid passing callbacks down? part of the Hooks FAQ. The argument passed to createContext will only be the default value if the component that uses useContext has no Provider above it further up the tree. You could instead create a Provider that supplies … Read more
Using hooks Hooks were introduced in 16.8.0 so the following code requires a minimum version of 16.8.0 (scroll down for the class components example). CodeSandbox Demo 1. Setting parent state for dynamic context Firstly, in order to have a dynamic context which can be passed to the consumers, I’ll use the parent’s state. This ensures … Read more
As Context is no longer an experimental feature and you can use Context in your application directly and it is going to be great for passing down data to deeply nested components which what it was designed for. As Mark Erikson has written in his blog: If you’re only using Redux to avoid passing down … Read more