Skip to content

组件实例

mount返回一个Vue wrapper,其中包含许多用于测试Vue组件的方便方法。有时您可能希望访问底层的Vue实例。可以通过vm属性访问。

一个简单的例子

下面是一个简单的组件,它结合了propsdata来渲染问候:

js
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");
});
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]
}
{
  msg1: [Getter/Setter],
  msg2: [Getter/Setter],
  hasOwnProperty: [Function]
}

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

getComponentfindComponent一起使用

getComponentfindComponent返回一个VueWrapper——很像从mount获取的那个。这意味着你还可以在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" });
});
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" });
});

更彻底的测试方法是针对呈现的内容进行断言。这样做意味着您断言传递和渲染的是正确的道具。

使用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
wrapper.findComponent(".foo"); // returns WrapperLike
wrapper.findComponent<typeof FooComponent>(".foo"); // returns VueWrapper
wrapper.findComponent<DefineComponent>(".foo"); // returns VueWrapper

结论

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