如何在 Jest 测试中访问 Vue-Composition-API 类型引用和“数据”?

Bri*_*yko 5 unit-testing vue.js vue-test-utils vuejs3 vue-composition-api

我目前正在处理一个遗留的 Vue 项目。我们正在使用带有选项 API 的 Vue 2.xw/Typescript。

我想提出切换到 Vue 组件 API 的案例,到目前为止,我认为这是一个非常引人注目的案例 - 除了一个缺点。

那就是——我们现有的测试失败了。具体来说,这是因为两个原因:

  1. 使用来自 '@vue/testUtils' 的 mount() 的测试不能使用 .setData() 方法手动设置数据(因为可观察状态是从 setup() 返回的,并且不再存在于数据中);

例子:

// FIXME: This test fails because Vue Test Utils .setData does not work
// with the new composition API.
it("renders by default", async () => {
  await wrapper.setData({
    crosshairCoordinates: [{ x: 0, y: 0 }],
  });
  expect(wrapper.findAllComponents(ChartTooltip).length)
    .toBe(1); // -> expected 1, recieved: 0
});
Run Code Online (Sandbox Code Playgroud)
  1. 通过 findComponent() 和 ref 字符串访问 dom 中的组件或 HTML 元素的测试不再找到新样式的 Refs

// FIXME: This test fails because Vue Test Utils findComponent doesn't work
// with the way Refs are handled with the Vue Composition API.
it("should be default and not emit event on mouse move", async () => {
  const chartWrapper = wrapper.findComponent({ ref: "wrapper" });
  chartWrapper.trigger("mousemove"); // -> TypeError Cannot read property 'ref' of undefined
  expect(wrapper.emitted("mousemove")).toBeFalsy();
});
Run Code Online (Sandbox Code Playgroud)

坦率地说,如果我能弄清楚如何解决这些问题,我可以提出一个完整的建议,迁移到 VueComponentAPI 并让一些开发人员非常高兴。如果我不能,那么我就不能推荐它,并且必须坚持使用 Vue Options API。

有任何想法吗?

小智 3

  1. 而不是wrapper.setData({foo: 'bar'})你可以使用wrapper.vm.foo = 'bar'
  2. 我相信 的行为wrapper.findComponent()没有任何改变。请记住,如果 ref 不是组件而是 html 元素,wrapper.findComponent({ ref: "foo" }) 可能会返回空包装器