How to test a react component that is dependent on useContext hook?

前端 未结 6 1851
情话喂你
情话喂你 2020-12-23 13:58

I have a component that uses useContext and then its output is dependent on the value in the context. A simple example:

import React, { useConte         


        
6条回答
  •  囚心锁ツ
    2020-12-23 14:40

    Or if you're testing your component in isolation without mounting the parent components you can simply mocking useContext:

    jest.mock('react', () => {
      const ActualReact = require.requireActual('react')
      return {
        ...ActualReact,
        useContext: () => ({ }), // what you want to return when useContext get fired goes here
      }
    })
    

    You can still use a dynamic useContext value with a global jest.fn

提交回复
热议问题