简体   繁体   English

将参数传递给笑话功能

[英]Passing parameters to jest function

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 但是,当我开玩笑说它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 当我console.log(handTotal('dealersHand')它记录了正确的事情,并且该功能正常工作,所以我知道它在做正确的事情

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 . 您对handleTotalStub开玩笑的间谍不会返回任何内容,因此它将返回undefined When your component tries to call handTotal('dealersHand').total it is therefore calling undefined.total , because handTotal(...) is not defined. 当您的组件尝试调用handTotal('dealersHand').total它会调用undefined.total ,因为undefined.total handTotal(...)

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) (其中SOME_VALUE是您可以模拟以充当组件期望的值的任何值)

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). 但是,永远不会调用实际的handTotal方法(这是一件好事,因为我们不在测试handTotal工作方式,而是在测试组件的工作方式)。

So, whatever handTotal would normally return is what you want to put in mockReturnValue() . 因此,通常要返回的handTotal就是您要放入mockReturnValue() So if handTotal returns an object like {total: 1} , then you would say mockReturnValue({total: 1}) 因此,如果handTotal返回一个类似{total: 1}的对象,那么您将说出mockReturnValue({total: 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM