如何将jest.spyOn与功能性React组件一起使用

时间:2020-01-16 22:16:39

标签: reactjs jestjs enzyme

我想测试当我使用handleAddBookToCart function单击按钮时是否调用Jest.spyOn

预先感谢您的帮助。

const HomeComponent = props => {
    const { addBookToCart } = props;

    const handleAddBookToCart = id => {
       addBookToCart(id);
    };

    return (
        <button onClick={() => handleAddBookToCart(id)}></button>
    )
}

//Container
const mapDispatchToProps = dispatch => ({
    addBookToCart: idBook => dispatch(cartOperations.addBookToCart(idBook))
});

//file test
describe('Test home component', () => {
   let container;
   let wrapper;
   let component;

   beforeEach(() => {
       wrapper = mount(
           <Provider store={store}>
               <HomeContainer />
           </Provider>
    );
    container = wrapper.find(HomeContainer);
    component = container.find(HomeComponent);

it('calls the handleAddBookToCart function when the button is clicked', () => {
    const spy = jest.spyOn(???)
    component.find('button').simulate('click');
    expect(spy).toHaveBeenCalled();
});

2 个答案:

答案 0 :(得分:2)

是否必须使用spyOn?您可以通过开玩笑的​​模拟fn作为addBookToCart道具


it('calls the handleAddBookToCart function when the button is clicked', () => {
   const props = {
     addBookToCart: jest.fn(),
     ...your other props
   }
   const component = shallow(<HomeComponent {...props} />)
    component.find('button').simulate('click');
    expect(props.addBookToCart).toHaveBeenCalled();
});

答案 1 :(得分:1)

一种简单的方法是将模拟发送到属性addBookToCart中,并在单击按钮时对其进行监视。

因此,当您为单元测试创​​建/安装/浅化组件时,请尝试以下操作(来自酶的安装,但可以使用现有的组件测试方法):

const spy = jest.fn();
const component = mount(<HomeComponent addBookToCart={spy} />);