使用 jest 测试组件时如何定位选择器的第一个 child

How to target first child of selector when testing component with jest

我正在尝试编写一个测试来确定是否使用 jestvue-test-utils 在 HTML 中正确传递了默认道具。我似乎找不到我的目标选择器。我希望能够测试特定的 p 标记是否包含正确的文本。在这种情况下,如果传递了 name 道具,它会呈现它。如果不是,则默认函数呈现默认 payTo 值。

我一直在尝试链接到包装器的几种组合,但都无济于事。

console.log(wrapper.html()) // presents all the page html
console.log(wrapper.classes()) // array showing only one class ('.row-space-between')

这是我的组件:

<template>
  <div class="row-space-between">
    <div>
      <h3>{{ $t('label.payTo') }}</h3>
      <p>{{ merchantName.payTo }}</p> // TARGET SELECTOR
    </div>
    <div class="align-right">
      <h3>{{ $t('label.estimatedTotal') }}</h3>
      <p>{{ amount }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PayTo',
  props: {
    'merchant-name': {
      type: Object,
      // default: {} with type obj or arr default function is required
      default: function () {
        return { merchantName: {
          payTo: 'Order Total'
         }
       }
    },
    amount: {
      type: String,
      default: ''
    }
  }
}

这是我的测试:

describe('PayTo.vue', () => {
  let wrapper

  beforeEach(() => {
    wrapper = shallowMount(PayTo, {
      mocks: {
        $t
      },
      propsData: {
        merchantName: {
          payTo: 'foo-merchant-name'
        },
        amount: '0.00'
      }
    })
  })
  it('[positive] should render correct contents', () => {
    // PayTo.props.merchantName.default()
    expect(wrapper.html()).toMatchSnapshot()
  })

  // The following two tests satisfy testing the default function in PayTo.vue props validation if not tested, coverage falls to zero

  // This test is meaningless until I can be more specific in targeting

  it('[positive] should display `AWS`', () => {
    wrapper.setProps({
      merchantName: {
        payTo: 'AWS'
      }
    })
    expect(wrapper.contains('p'))
  })

  it('[negative] should display `Order Total`', () => {
    wrapper.setProps({
      merchantName: {
        payTo: 'Order Total'
      }
    })
    console.log(wrapper.contains('div > p'))
    expect(wrapper.contains('p'))
  })

这里可以使用:first-child伪class:

expect(wrapper.contains("div:first-child > p")).toBeTruthy()

我还会验证 p 中的文本是否符合预期值:

expect(wrapper.find("div:first-child > p").text()).toBe("Order Total")

另请注意,您的 merchant-name 道具的默认值不应包含另一个 merchantName 键。否则,当未指定该道具时,payTo 将被 merchantName.merchantName.payTo.

访问
props: {
  "merchant-name": {
    type: Object,
    default: function() {
      return {
        // merchantName: {  // DON'T DO THIS
        //  payTo: "Order Total"
        // }

        payTo: "Order Total"
      }
    }
  },
}