我想测试当我使用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();
});
答案 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} />);