Skip to content

Is it is possible to test only one function from component with Jest?

I have react component, for example something like this:

const MyComponent = (props) => {
  const [state, setState] = useState(true);
  const {data} = useContext(myContext);
  const location = useLocation();

  //A lot of code here

  const myFunction = () => {
    return { dataFromContext: data, locationFromUseLocation: location, state: state }
  }

  return <>A lot of other components here</>
}

And I’m trying to write test that should looks like this:

describe('Component test', () => {
 it('myFunction test', () => {
    const wrapper = shallow(<MyComponent/>);
    const expectedResult = {
      dataFromContext: 'any data here', 
      locationFromUseLocation: 'any location here', 
      state: false
};
    expect(wrapper.dive().instance().myFunction()).toEqual(expectedResult);
  })
})

Can I mock useState, useContext and useLocation from <MyComponent/> and pass my custom data instead of real data from real component?

Answer

After deeper researching I’ve understood, that in such situation I can’t write test only for function in my component. So, I’ve created unit-test, that tests all my component, not only one function.