Passing parameters to jest function
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})
The Walrus
Updated on June 04, 2022Comments
-
The Walrus almost 2 years
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 thingI'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); });
-
The Walrus about 6 yearsok cheers, but I've done that and it now thinks the whole function is undefined or rather
expected: 1, received: undefined
? -
Jason Spradlin about 6 yearsYou're going to need to post the actual test. I can't see where you're saying
expect(...)...
-
Jason Spradlin about 6 yearsSorry, also update how you created the stub (what does it return??)
-
The Walrus about 6 yearsadded that too.
-
The Walrus about 6 yearsah ok nice one, but in terms of actually testing that function, shall I do that in the component above where it is defined?
-
Jason Spradlin about 6 yearsNot sure. That would take knowing what the rest of the component and its parent and all that look like. That might need to be a different question from this one.