У меня есть такой компонент, как ниже, и я хочу запустить тест для функции onClick этого.Но тест не удался, так как он не может найти компонент и имитировать функцию щелчка.Что я сделал не так и как я могу решить эту проблему?
компонент
<Block
justify="flex-end"
alignItems="flex-end"
width={2}
className="cancel"
onPress={() => {
onCancelDelete()
}}
>
<FIcon
size={25}
color={Colors.fire}
name="x-circle"
/>
</Block>
Весь код компонента пользовательского интерфейса можно найти в прикрепленном файле.
Контрольный пример
test('cancel delete button onclick event', () => {
const wrapper = shallow(<Stock {...props} />)
const cancelButton = wrapper.find('Block.cancel')
expect(cancelButton.length).toBe(1)
cancelButton.simulate('click')
expect(wrapper.state().confirmDelete).toBeFalsy()
})
Для справки
Внешняя оболочка компонента пользовательского интерфейса - это компонент "ActionWrapper", который является стилемиспользуя стилизованные компоненты. Если я выполню следующий тест, он пройдет для этого компонента
test('cancel delete button onclick event', () => {
const wrapper = shallow(<Stock {...props} />)
const cancelButton = wrapper.find('Block.cancel')
expect(cancelButton.length).toBe(1)
})
UI компонента
// react core
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createStructuredSelector } from 'reselect'
// partials
import { ProductImage } from './Partials/ProductImage'
const mapStateToProps = createStructuredSelector({
})
const mapDispatchToProps = dispatch => ({
})
export class Stock extends Component {
state = {
openCard: false,
showCard: false,
confirmDelete: false
}
// to show product details
onCard = openCard => {
}
// to show and close add to stock option
_ShowCard = () => {
}
// onDlete Stock
onDeleteStock = data => {
}
// update the products
handlesubmit = data => {
}
onUpdate = data => {
}
onCancelDelete = () => {
}
onGetStock = () => {
}
componentDidMount() {
this.onGetStock()
}
render() {
let {
props: { stockProducts, error, products, fetching },
state: { openCard, showCard, confirmDelete },
onCard,
onGetStock,
_ShowCard,
handlesubmit,
onUpdate,
onDeleteStock,
onCancelDelete
} = this
return (
<KeyboardAvoidingWrapper fluid enabled={!showCard}>
<ActionWrapper
title="In stock"
description={'Manage your in stock items'}
actions={
!showCard
? [
{
name: 'Add to stock',
desc: 'You can add an item from your products',
icon: 'plus-circle',
onPress: () => {
_ShowCard()
}
}
]
: []
}
busy={fetching}
onRefresh={onGetStock}
withSearch
data={stockProducts}
>
{stockProducts => (
<FormProvider>
<Wrapper>
<Spacer size={10} />
{stockProducts.map(
(
{
name,
price,
vendorPrice,
amount,
stock = {},
_id,
image = {}
},
key
) => (
<Card snow buffer key={_id}>
<Row fluid inline>
<ProductImage
compact
flickr_id={
image.flickr_id ? image.flickr_id : '41547729080'
}
/>
<Block width={8}>
<P compact uppercase>
<P compact bold>
{stock.quantity}
</P>{' '}
x {name}
</P>
<P compact bold>
In stock
</P>
<P small compact>
{currencyMask(vendorPrice)} per each
</P>
<P compact small>
Created At :{' '}
{moment(stock.createdAt).format('YYYY-MM-DD')}
</P>
</Block>
<Block
justify="center"
alignItems="center"
onPress={() => {
onCard(openCard === _id ? false : _id)
}}
>
<FIcon
size={25}
name={
openCard === _id ? 'chevron-up' : 'chevron-down'
}
/>
</Block>
</Row>
{openCard === _id && (
<FormBridge>
{({ handleChange, formState }) => (
<React.Fragment>
<HorizontalLine />
<Row fluid justify="center">
{confirmDelete !== true ? (
<Block
justify="flex-end"
fluid
width={2}
onPress={() => {
onDeleteStock({ _id: _id })
}}
>
<FIcon
size={25}
color={Colors.fire}
name="trash"
/>
</Block>
) : (
<React.Fragment>
<Block
justify="flex-end"
width={2}
alignItems="flex-start"
>
<BorderButton
text="confirm"
onPress={() => {
onDeleteStock({ _id: _id })
}}
/>
</Block>
<Block
justify="flex-end"
alignItems="flex-end"
width={2}
className="cancel"
onPress={() => {
onCancelDelete()
}}
>
<FIcon
size={25}
color={Colors.fire}
name="x-circle"
/>
</Block>
</React.Fragment>
)}
{confirmDelete === false && (
<React.Fragment>
<Block
justify="flex-end"
alignItems="stretch"
width={5}
>
<P small center>
Quantity
</P>
{/*eslint-disable */}
<Row fluid>
{formState['quantityUpdate'] &&
formState['quantityUpdate'].value >
1 && (
<Block
fluid
justify="center"
alignItems="center"
onPress={() => {
if (
formState['quantityUpdate'] &&
!parseInt(
formState['quantityUpdate']
.value
) <= 0
) {
handleChange(
'quantityUpdate',
`${parseInt(
formState[
'quantityUpdate'
].value
) - 1}`
)
} else {
handleChange(
'quantityUpdate',
'0'
)
}
}}
>
<FIcon
size={20}
color={Colors.fire}
name="minus-square"
/>
</Block>
)}
<Block width={3} fluid>
<FormInput
name="quantityUpdate"
defaultValue={`${stock.quantity}`}
label={'Quantity'}
compact
numeric
keyboardType="phone-pad"
/>
</Block>
<Block
fluid
justify="center"
alignItems="center"
onPress={() => {
handleChange(
'quantityUpdate',
`${parseInt(
formState['quantityUpdate']
.value
) + 1}`
)
}}
>
<FIcon
size={20}
color={Colors.facebook}
name="plus-square"
/>
</Block>
</Row>
{/* eslint-enable */}
</Block>
<Block justify="flex-end" fluid width={3}>
<BorderButton
compact
text="Update"
onPress={e => {
onUpdate({
id: _id,
quantity:
formState['quantityUpdate'].value
})
}}
/>
</Block>
</React.Fragment>
)}
</Row>
</React.Fragment>
)}
</FormBridge>
)}
</Card>
)
)}
</Wrapper>
</FormProvider>
)}
</ActionWrapper>
</KeyboardAvoidingWrapper>
)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Stock)