三、测试样式和结构

到目前为止,我们已经使用玩笑快照进行了测试 https://facebook.github.io/jest/docs/snapshot-testing.html )。在大多数情况下,这是我们将使用的,但有时我们可能希望断言更具体的东西。

虽然您可以通过cmp.vm访问 Vue 实例 https://github.com/alexjoverm/vue-testing-series/blob/master/test/MessageList.test.js#L17 ),您可以使用一套实用程序来简化操作。让我们看看我们能做些什么。

包装器对象

Wrappervue-test-utils的主要对象。是mountshallowMountfindfindAll函数返回的类型。你可以在这里看到整个 API 和打字https://github.com/vuejs/vue-test-utils/blob/v1.0.0-beta.27/packages/test-utils/types/index.d.ts

**## 找到并找到

findfindAll接受选择器https://github.com/vuejs/vue-test-utils/blob/v1.0.0-beta.27/packages/test-utils/types/index.d.ts#L92 )作为参数,可以是 CSS 选择器,也可以是 Vue 组件。

因此,我们可以采取以下措施:

let cmp = mount(MessageList);
expect(cmp.find(".message").element).toBeInstanceOf(HTMLElement);
// Or even call it multiple times
let el = cmp.find(".message").find("span").element;
// Although for the previous example, we could do it in one
let el = cmp.find(".message span").element;

断言结构和风格

让我们在MessageList.test.js中添加更多测试:

it("is a MessageList component", () => {
  expect(cmp.is(MessageList)).toBe(true);
  // Or with CSS selector
  expect(cmp.is("ul")).toBe(true);
});
it("contains a Message component", () => {
  expect(cmp.contains(Message)).toBe(true);
  // Or with CSS selector
  expect(cmp.contains(".message")).toBe(true);
});

在这里,我们使用is断言根组件类型,并使用contains检查子组件的存在。就像find一样,它们接收一个选择器,可以是 CSS 选择器或组件。

我们有一些 UTIL 来断言Vue 实例

it("Both MessageList and Message are vue instances", () => {
  expect(cmp.isVueInstance()).toBe(true);
  expect(cmp.find(Message).isVueInstance()).toBe(true);
});

现在我们将更详细地断言结构

it("Message element exists", () => {
  expect(cmp.find(".message").exists()).toBe(true);
});
it("Message is not empty", () => {
  expect(cmp.find(Message).isEmpty()).toBe(false);
});
it('Message has a class attribute set to "message"', () => {
  expect(cmp.find(Message).attributes().class).toBe("message");
});

existsisEmptyattributes方法对此很方便。

然后,我们有classesattributes().style来断言样式。让我们用样式更新Message.vue组件,因为attributes().style只声明内联样式:

<li style="margin-top: 10px" class="message">{{message}}</li>

以下是测试:

it("Message component has the .message class", () => {
  expect(cmp.find(Message).classes()).toContain("message");
});
it("Message component has style padding-top: 10", () => {
  expect(cmp.find(Message).attributes().style).toBe("padding-top: 10px;");
});

有很多 UTIL 可以使测试 Vue 组件更容易。您可以在打字文件中找到它们 https://github.com/vuejs/vue-test-utils/blob/v1.0.0-beta.27/packages/test-utils/types/index.d.ts )。

您可以在GitHub上找到本章的工作代码 https://github.com/alexjoverm/vue-testing-series/blob/Test-Styles-and-Structure-in-Vue-js-and-Jest/test/MessageList.test.js )。**