跳至内容

组件实例

mount 返回一个 VueWrapper,它包含许多用于测试 Vue 组件的便捷方法。有时你可能需要访问底层的 Vue 实例。你可以使用 vm 属性访问它。

一个简单的例子

这是一个简单的组件,它结合了 props 和 data 来渲染问候语

ts
test('renders a greeting', () => {
  const Comp = {
    template: `<div>{{ msg1 }} {{ msg2 }}</div>`,
    props: ['msg1'],
    data() {
      return {
        msg2: 'world'
      }
    }
  }

  const wrapper = mount(Comp, {
    props: {
      msg1: 'hello'
    }
  })

  expect(wrapper.html()).toContain('hello world')
})

让我们通过 console.log(wrapper.vm) 来看看 vm 上有哪些内容

js
{
  msg1: [Getter/Setter],
  msg2: [Getter/Setter],
  hasOwnProperty: [Function]
}

我们可以看到 msg1msg2!如果定义了 methodscomputed 属性,它们也会显示出来。在编写测试时,虽然通常建议针对 DOM 进行断言(使用类似 wrapper.html() 的东西),但在某些情况下,你可能需要访问底层的 Vue 实例。

getComponentfindComponent 一起使用

getComponentfindComponent 返回一个 VueWrapper - 非常类似于从 mount 获取的 VueWrapper。这意味着你也可以访问 getComponentfindComponent 结果上的所有相同属性,包括 vm

这是一个简单的例子

js
test('asserts correct props are passed', () => {
  const Foo = {
    props: ['msg'],
    template: `<div>{{ msg }}</div>`
  }

  const Comp = {
    components: { Foo },
    template: `<div><foo msg="hello world" /></div>`
  }

  const wrapper = mount(Comp)

  expect(wrapper.getComponent(Foo).vm.msg).toBe('hello world')
  expect(wrapper.getComponent(Foo).props()).toEqual({ msg: 'hello world' })
})

测试此组件的更彻底的方法是针对渲染的内容进行断言。这样做意味着你断言传递了正确的 prop,并且它也被渲染了。

使用 CSS 选择器时的 WrapperLike 类型

例如,当使用 wrapper.findComponent('.foo') 时,VTU 将返回 WrapperLike 类型。这是因为函数式组件需要一个 DOMWrapper,否则就是一个 VueWrapper。你可以通过提供正确的组件类型来强制返回一个 VueWrapper

typescript
wrapper.findComponent('.foo') // returns WrapperLike
wrapper.findComponent<typeof FooComponent>('.foo') // returns VueWrapper
wrapper.findComponent<DefineComponent>('.foo') // returns VueWrapper

结论

  • 使用 vm 访问内部 Vue 实例
  • getComponentfindComponent 返回一个 Vue 包装器。这些 Vue 实例也可以通过 vm 获得