lundi 11 février 2019

Enzyme/Jest Context API Injection (React) Not Working

So I want to test a component that uses React's context api and it's not working. It should be seemingly pretty simple - as stated here (React js - How to mock Context when testing component) all you would have to do is something like this:

const context = { name: 'foo' };
const wrapper = mount(<SimpleComponent />, { context });

However, I have something very similar and it doesn't seem to be picking up on it.

Here is my test file -

import * as React from 'react'
import Enzyme, { shallow, mount } from "enzyme";
import Home from '../pages/home/index'
import Adapter from "enzyme-adapter-react-16";

import stateVals from '../__mocks__/stateVals';

console.log('value of stateVals: ', stateVals)

describe('Pages', () => {
  describe('Index', () => {
    it('should render without throwing an error', function () {
      const wrap = mount(<Home/>, { stateData: { state: stateVals } })
      expect(wrap.find('div').text()).toBe('hello there main home')
    })
  })  
})

Here is my stateVals object I import:

const stateVals = {
  ContextNext: "ldjkfs",
  route: "/home",
  styledcomponent: "sfsdfsdfsdf",
  name: "dfasfasfasdf", 
  renderCloseAbout: false,
  aboutCardStatus: "closed",
  uploadedHistory: null, 
  greptchaTime: Date.now(), 
  loginStatus: "initial",
  registrationStatus: "N/A",
  userEmail: "N/A",
  completeRegistration: {}, 
  pageVal: "", 
  addPurchaseSubsJSON: ["empty"], 
  admins: ['SUPERDOOPERSECRET'],
  modal: {
    open: false, 
    message: ''
  }
}
export default stateVals

And here is the beginning of the component I want to test -

class Home extends Component {

  render(){
    return(
      <MainContext.Consumer>
      {stateData => {
        return(
          <div className='grid-container abspos'>
            {renderIf(stateData.state.modal.open==true)(
              <Modal/>
            )}

It throws this error:

TypeError: Cannot read property 'state' of undefined

  26 |         return(
  27 |           <div className='grid-container abspos'>
> 28 |             {renderIf(stateData.state.modal.open==true)(
     |                                 ^
  29 |               <Modal/>
  30 |             )}

Why is this happening?

Aucun commentaire:

Enregistrer un commentaire