mardi 2 juin 2020

React testing project ... (node:12592) UnhandledPromiseRejectionWarning: (rejection id: 1)

I'm testing out my Move In/Out buttons for my React App, I got this giant error:

TypeError: Cannot read property 'name' of undefined

      156 |          props.moveIn(cityObj, inputValue)
      157 |          props.errorMsg('')
    > 158 |          props.userMsg(`Added ${inputValue} to ${cityObj.name}`)
          |                                                          ^
      159 |          clearField()
      160 |          setInputChange('')
      161 |       } else {
(node:12592) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

And...

 console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Uncaught [TypeError: Cannot read property 'name' of undefined]
        at reportException (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:66:24)
        at invokeEventListeners (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:209:9)
        at HTMLUnknownElementImpl._dispatch (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:119:9)
        at HTMLUnknownElementImpl.dispatchEvent (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:82:17)
        at HTMLUnknownElementImpl.dispatchEvent (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\nodes\HTMLElement-impl.js:30:27)
        at HTMLUnknownElement.dispatchEvent (C:\code\cohort4\react-02\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:157:21)
        at Object.invokeGuardedCallbackDev (C:\code\cohort4\react-02\node_modules\react-dom\cjs\react-dom.development.js:237:16)
        at invokeGuardedCallback (C:\code\cohort4\react-02\node_modules\react-dom\cjs\react-dom.development.js:292:31)
        at invokeGuardedCallbackAndCatchFirstError (C:\code\cohort4\react-02\node_modules\react-dom\cjs\react-dom.development.js:306:25)
        at executeDispatch (C:\code\cohort4\react-02\node_modules\react-dom\cjs\react-dom.development.js:389:3) TypeError: Cannot read property 'name' of undefined
        at onMoveIn (C:\code\cohort4\react-02\src\components\Cities\components\CityCards.js:158:58)
        at HTMLUnknownElement.callCallback (C:\code\cohort4\react-02\node_modules\react-dom\cjs\react-dom.development.js:188:14)

... which goes on for a while. This is a tricky part for me, I'm simply trying to simulate change of the input value then click on Move In, and then I expect it to return a message saying '5 moved into Calgary', my functions and my React app works great, however I can't get this test to pass.

My React code ---- Main App/Component where the move in function is:

   async function moveIn(thekey, num) {
      await cityCtrl.movedIn(thekey, num)
      setCount(count + 1)
      updateSummary()
   }

My Javascript pure function kept in another file: (I am exporting this to React as used above)

async movedIn(city, num) {
        let theUrl
        if (city.key) {
            city.population += Number(num)
            theUrl = url + 'update'
        }
        await postData(theUrl, city)
    }

My CityCards component - the input field (I am using Material UI):

<List className={classes.list}>
                     <ListItem className={classes.listItemInput} >
                        <TextField label='#' htmlFor='hi' type='number' onChange={handleInputChange} className='inputBox'
                           inputProps=data-testid name='inputChange' />
                     </ListItem>
                  </List>
                  <CardActions className={classes.buttonArea}>
                     <Button variant="outlined" color="primary" onClick={onMoveIn}>Moved In</Button>

CityCards component where it uses the Move In function prop:

   function onMoveIn(e) {
      let thekey = e.currentTarget.parentNode.parentNode.parentNode.getAttribute('mykey')
      const cityObj = props.cityCtrl.get(thekey)
      if (inputValue > 0) {
         props.moveIn(cityObj, inputValue)
         props.errorMsg('')
         props.userMsg(`${inputValue} moved to ${cityObj.name}`)
         clearField()
         setInputChange('')
      } else {
         props.userMsg('')
         props.errorMsg('Population increase must be atleast 1')
      }
   }

Finally, my test:

import React from 'react'
import { fireEvent, render, screen } from '@testing-library/react';
import CityCards from '../CityCards'
import funcs from '../../business/functions'

test('Test the card Move In/Out functionality', () => {
   const cityCtrl = new funcs.Community()

   const mockMoveInCallBack = jest.fn()
   const mockMoveOutCallBack = jest.fn()
   const mockDeleteCallBack = jest.fn()
   const mockMsgCallBack = jest.fn()
   const mockErrorMsgCallBack = jest.fn()
   const mockHandleChangeCallBack = jest.fn()

   const fakeCities = {
      1: { key: 1, name: 'Calgary', latitude: 5, longitude: 10, population: 1000 }
   };

   render(<CityCards
      cityCtrl={cityCtrl}
      cities={fakeCities}
      userMsg={mockMsgCallBack}
      errorMsg={mockErrorMsgCallBack}
      moveIn={mockMoveInCallBack}
      moveOut={mockMoveOutCallBack}
      deleteCard={mockDeleteCallBack}
      handleInputChange={mockHandleChangeCallBack}
   />)

   screen.getByText('Calgary')

   click(/Moved In/i)

   expect(mockErrorMsgCallBack.mock.calls.length).toBe(1)
   expect(mockErrorMsgCallBack.mock.calls[0][0]).toBe('Population increase must be atleast 1')

   let input = screen.getByTestId('content-input')
   fireEvent.change(input, { target: { value: '23' } })
   click(/Moved In/i)//It is having an error here I believe

   expect(mockErrorMsgCallBack.mock.calls[1][0]).toBe('5 moved to Calgary')
   expect(mockMsgCallBack.mock.calls.length).toBe(2)

})

function click(txt) {
   fireEvent.click(
      screen.getByText(txt)
   );
}

Any input is appreciated. Thanks for reading.

Aucun commentaire:

Enregistrer un commentaire