Testa React-komponenter med useContext-hook

När man skall testa en React-komponent som använder hooken useContext med Enzymes ShallowWrapper kan man använda sig av en hjälpkomponent som förändrar context enligt följande kodexempel:

import React, {
  useContext
} from 'react'
import { shallow } from 'enzyme'

interface MyContextType {
  data: string;
}
const MyContext = React.createContext<MyContextType>(
  {data: 'default'}
)

// Helper component whose purpose is to make it possible to 
// modify the context
interface ModifyContextProps {
  changeContext: (context: MyContextType) => void;
}
function ModifyMyContext({changeContext}: ModifyContextProps) {
  const context = React.useContext(MyContext)
  changeContext(context)
  return null
}

// Component using the context via hooks
function XXX() {
  const context = useContext(MyContext)
  return (
    <div>{context.data}</div>
  )
}

describe('XXX', () => {
  it('should use context', () => {
    // Set context values
    shallow(
      <ModifyMyContext changeContext={
        (c) => c.data='Some new info'
      }/>
    )
    const wrapper = shallow(<XXX/>)

    expect(wrapper.text()).toContain('Some new info')
  })    
})


IT consultant and Java specialist at CAG Contactor.

Publicerad i Context, Enzyme, Frontend, Hooks, React Taggar: , , , ,

Kategorier

WP to LinkedIn Auto Publish Powered By : XYZScripts.com