使用Jest来断言函数是从另一个函数中调用的

blu*_*ler 9 javascript frontend unit-testing reactjs jestjs

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

this.props.onChangeImage()
Run Code Online (Sandbox Code Playgroud)

在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>);
  }
}
Run Code Online (Sandbox Code Playgroud)

下面,在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);
Run Code Online (Sandbox Code Playgroud)

我在这里看了很多答案,虽然这个答案看起来最接近,但它并不能让我在那里:Jest - 嘲笑函数调用

编辑:这是我的测试,我认为这是错误的,因为它指定模拟函数直接调用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();
  });
}
Run Code Online (Sandbox Code Playgroud)

Har*_*dha 11

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

  1. sendEventToParentWindow 模拟功能.
  2. onChangeImage带有实现的mock函数,其中实现只包含对sendEventToParentWindowmock函数的调用.

所以测试看起来像这样,

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();
  });
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)