玩笑,用酶测试同一子组件的多次出现

问题描述 投票:0回答:1

我正在尝试测试模拟内容在测试中是否正确显示。其中两个使用H2Tag组件,而另一个使用H1Tag组件。由于要测试两个不同的字符串,因此我无法正确进行H2Tag组件的测试。

是否有一种方法可以测试同一组件(使用不同的输入道具)是否多次出现?或者,是否有更好的方法来完成此测试?

我也在使用样式化组件,因此组件名称在debug()中显得略有不同。

const Partner = ({ content }) => {
  return (
      <ContentWrapper>
        <H1Tag>{content.headline}</H1Tag>
        <H4Tag>{content.heading1}</H4Tag>
        <H1Tag>{content.heading2}</H1Tag>
      </ContentWrapper>
  )
}
//Partner.test.js
import React from 'react'
import Partner, { H1Tag, H4Tag,} from '../SomePage'
import { shallow } from 'enzyme'

describe('Partner', function () {
  beforeAll(() => {
    this.mockContent = {
      headline: 'Partner',
      heading1: 'Hello',
      heading2:
        'ABC XYZ',
    }
  })

  beforeEach(() => {
    this.wrapper = shallow(
      <Partner content={this.mockContent} />
    )
  })

  describe('render', () => {
    it('shows H1Tags content', () => {
      const H1TagWrapper = this.wrapper.find(H1Tag)

      const { headline, heading2 } = this.mockContent
      // how to test two different elements?
      expect(H1TagWrapper.getElements()).toBe([headline, heading2]) //this fails
    })

    it('shows H4Tag content', () => {
      const H4TagWrapper = this.wrapper.find(H4Tag)
      expect(H4TagWrapper.text()).toEqual(this.mockContent.heading1) //this works
    })
  })
})

这是当前方法的预期/接收结果。

    expect(received).toBe(expected) // Object.is equality

    - Expected
    + Received

      Array [
    -   "Partner",
    -   "ABC XYZ",
    +   <ForwardRef(PartnerBanner__H1Tag)>
    +     Partner
    +   </ForwardRef(PartnerBanner__H1Tag)>,
    +   <ForwardRef(PartnerBanner__H1Tag)>
    +     ABC XYZ
    +   </ForwardRef(PartnerBanner__H1Tag)>,
reactjs enzyme styled-components jest
1个回答
0
投票

基于@Fanchen Bao的评论(非常感谢!):

如果要测试的子组件出现两次,则使用.first()和.last()将起作用。

如果子组件出现两次以上,例如5使用.at(0)... .at(4)也可以。

// these two are the same in this question's context
expect(H1TagWrapper.first().text()).toBe(headline) 
expect(H1TagWrapper.last().text()).toBe(heading2)

expect(H1TagWrapper.at(0).text()).toBe(headline)
expect(H1TagWrapper.at(0).text()).toBe(heading2)
© www.soinside.com 2019 - 2024. All rights reserved.