Source:  Twitter logo

I have this function in my child component:

<div> {handTotal('dealersHand').total} </div>

This has been passed down from above

however when I run jest it says Cannot read property 'total' of undefined

when i console.log(handTotal('dealersHand') it is logging the right thing and the function works so I know it's doing the correct thing

I've stubbed it out in jest like so:

const handTotalStub = jest.fn()
  beforeEach(() => {
    wrapper = mount(<Dealer
      dealersHand={dealersHandStub}
      containsAce={containsAceStub}
      handTotal={handTotalStub}
    />);
  })

How do I pass the parameter into this function so that jest understands what it is?

can add more code/explanation if doesn't make sense

stubbing:

  const handTotalStub = jest.fn().mockReturnValue('dealersHand')

test:

  it('expects dealers hand to equal', () => {
    expect(handTotalStub('dealersHand').total).toEqual(1);
  });

Your jest spy for handleTotalStub does not return anything, so it therefore returns undefined. When your component tries to call handTotal('dealersHand').total it is therefore calling undefined.total, because handTotal(...) is not defined.

Update your spy to return something (anything) by changing

handTotalStub = jest.fn();

to

handTotalStub = jest.fn().mockReturnValue(SOME_VALUE);

or

handTotalStub = jest.fn().mockImplementation(() => SOME_VALUE);

(where SOME_VALUE is any value that you can mock out to act as what the component expects to be there)

EDIT -- Ok, so you're misunderstanding what mockReturnValue does. You don't have to mock the parameters being passed in to that method. Because your component is already passing in that string. BUT, the actual handTotal method is never going to be called (this is a good thing, because we're not testing how handTotal works, we're testing how the component works).

So, whatever handTotal would normally return is what you want to put in mockReturnValue(). So if handTotal returns an object like {total: 1}, then you would say mockReturnValue({total: 1})

3 users liked answer #0dislike answer #03
Jason Spradlin profile pic
Jason Spradlin

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).