I have created a LauoutContext.js
for my application needs. Also used router
location to get the URL / pathname. And passing reducer to child.
JS File: LayoutContext.js
import React, { createContext, useReducer } from 'react'
import PropTypes from 'prop-types'
import Dashboard from '../components/layouts/primary/Dashboard'
import layoutReducer from '../reducers/layoutReducer'
import { useLocation } from 'react-router-dom'
export const LayoutContext = createContext()
const LayoutContextProvider = (props) => {
const [leftDrawerSelectedItem, layoutDispatch] = useReducer(
layoutReducer,
useLocation().pathname
)
return (
<LayoutContext.Provider value={{ leftDrawerSelectedItem, layoutDispatch }}>
<Dashboard>{props.children}</Dashboard>
</LayoutContext.Provider>
)
}
LayoutContextProvider.propTypes = {
children: PropTypes.object
}
export default LayoutContextProvider
Test File: LayoutContext.test.js
import React, { createContext, useReducer } from 'react'
import { render, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import LayoutContext from '../LayoutContext'
import Dashboard from '../Dashboard'
import LayoutContextProvider from '../LayoutContext'
test('LayoutContext test', () => {
const tree = (
<LayoutContext.Provider value={null}>
<Dashboard />
</LayoutContext.Provider>
)
const { getByText } = render(tree)
expect(getByText('Something')).toBeInTheDocument()
})
Error:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
How can I test this Context?
Here Dashboard.js file:
const Dashboard = (props) => {
const { children } = props
const classes = useStyles()
let location = useLocation()
return (
<div className={classes.root}>
<main className={classes.main}>{children}</main>
</div>
)
}
Dashboard.propTypes = {
children: PropTypes.node
}
export default Dashboard
useLocation
is for react-router-dom you need to mock it or wrapping the component withBrowserRouter
in the test.