Javascript 使用 Jest 来断言一个函数是从另一个函数内部调用的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45102922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:55:01  来源:igfitidea点击:

Using Jest to assert a function is called from within another function

javascriptreactjsunit-testingjestjsfrontend

提问by blueyodeler

I have a component in React with an onChange event. In the code below, I need to assert that the correct method is called when

我在 React 中有一个带有 onChange 事件的组件。在下面的代码中,我需要断言调用正确的方法时

this.props.onChangeImage()

is invoked in the Gallery component.

在 Gallery 组件中调用。

export class Form extends React.PureComponent {

  componentDidMount = () => {
    this.props.getUser();
    this.props.getImages();
    this.props.getBoards();
  }

  render() {
    if (this.props.pin === null) {
      let boards = [];
      boards = this.props.boards;
      boards = boards.data.map(
        (item) => <MenuItem key={item.id.toString()} value={item.name} primaryText={item.name} />
      );
      return (
        <div>
          <Helmet
            title="Form"
            meta={[
              { name: 'description', content: 'Description of Form' },
            ]}
          />
          <Gallery images={this.props.images} onChange={this.props.onChangeImage} />
        </div>
      );
    }
    return (<div className="spinner-container"><CircularProgress /></div>);
  }
}

Below, in the onChangeImage method, I am trying to assert that the sendEventToParentWindow method is called.

下面,在 onChangeImage 方法中,我试图断言调用了 sendEventToParentWindow 方法。

function mapDispatchToProps(dispatch) {
  return {

    onChangeImage: (event) => {
      dispatch(createPinImage(event.target.value));
      sendEventToParentWindow({
        action: 'change-image',
        description: 'Change image',
      });
    },
  };
}

function sendEventToParentWindow(message) {
  window.postMessage(message, window.location.href);
}

export default connect(mapStateToProps, mapDispatchToProps)(Form);

I've looked at a number of answers here, and while this one seemed closest, it's not quite getting me there: Jest - mocking a function call

我在这里查看了许多答案,虽然这个答案似乎最接近,但它并没有让我到达那里:Jest - mocking a function call

EDIT: Here is my test which I believe is wrong because it's assigning the mocked function to be called directly onChange when it really should be calling the function that in turn calls the mock. I need somehow to invoke the onImageChange function and then verify that my spy was called.

编辑:这是我的测试,我认为它是错误的,因为它分配模拟函数直接在 onChange 调用,而实际上应该调用该函数,而该函数又调用模拟。我需要以某种方式调用 onImageChange 函数,然后验证是否调用了我的间谍。

import Gallery from '../index';
import * as formIndex from '../../../containers/Form';

describe('<Gallery />', () => {
  it('Expect sendMessageToParentWindow to be called on image change', () => {
    const sendEventToParentWindowMock = jest.spyOn(formIndex, 'sendEventToParentWindow');
    const gallery = shallow(<Gallery images={imagesMockData} onChange={sendEventToParentWindowMock} />);
    gallery.find('input#image-1').simulate('change');

    expect(sendEventToParentWindowMock).toBeCalled();
  });
}

回答by Hardik Modha

As I mentioned in the comment, You can pass a mocked function as prop whose implementation will contain a call to your sendEventToParentWindowfunction. i.e. You'll need to create two mocked function.

正如我在评论中提到的,您可以将模拟函数作为 prop 传递,其实现将包含对您的sendEventToParentWindow函数的调用。即您需要创建两个模拟函数。

  1. sendEventToParentWindowmock function.
  2. onChangeImagemock function with implementation, where implementation will only contain call to your sendEventToParentWindowmock function.
  1. sendEventToParentWindow模拟功能。
  2. onChangeImage带有实现的模拟函数,其中实现将只包含对sendEventToParentWindow模拟函数的调用。

So the test will look something like this,

所以测试看起来像这样,

describe('<Gallery />', () => {
  it('Expect sendMessageToParentWindow to be called on image change', () => {
    const sendEventToParentWindowMock = jest.fn();
    const onChangeImageMock = jest.fn(() => {
         sendEventToParentWindowMock();
    });

    const gallery = shallow(<Gallery images={imagesMockData} onChange={onChangeImageMock} />); // Passing the mocked onChangeImage as prop
    gallery.find('input#image-1').simulate('change');

    expect(sendEventToParentWindowMock).toBeCalled();
  });
}

Hope it helps :)

希望能帮助到你 :)