首页 > 解决方案 > 无法模拟使用样式组件设置样式的组件的 onclick 功能

问题描述

我有一个像波纹管这样的组件,我想为它的 onClick 功能运行一个测试。但测试失败,因为它找不到组件并模拟点击功能。我做错了什么,我该如何解决?

零件

<Block
  justify="flex-end"
  alignItems="flex-end"
  width={2}
  className="cancel"
  onPress={() => {
    onCancelDelete()
  }}
>
  <FIcon
    size={25}
    color={Colors.fire}
    name="x-circle"
  />
</Block>

ui 组件的完整代码可以在附件中找到。

测试用例

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()
})

以供参考

ui 组件最外层的包装器是一个名为“ActionWrapper”的组件,它是使用 Styled 组件的样式。如果我运行以下测试,它将通过该组件

test('cancel delete button onclick event', () => {
const wrapper = shallow(<Stock {...props} />)
      const cancelButton = wrapper.find('Block.cancel')
      expect(cancelButton.length).toBe(1)
})

界面组件

// 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)

标签: javascriptreactjsreact-nativeecmascript-6jestjs

解决方案


推荐阅读