Vue.js 中的 Jest 快照测试简介

介绍

Snapshot testing是Jest中的一种测试,它监测您的代码中的回归,同时也作为集成测试。第一种意思是,如果您将更多的代码添加到您的项目中,并且一些小东西被打破,即时测试可以捕捉到它。

快照测试的工作方式是,第一次运行jest,快照是由DOM生成的。在测试套件的后续运行中,已构建的DOM与这些快照进行比较。

有些问题自然会出现:如果我对你的程序做出重大改变,从而产生不同的DOM内容? Jest允许你生成新的快照,这样的场景会证明这一点。

App 设置

现在我们将设置我们的应用程序。 转到我们的 使用 Jest 测试视觉的教程的设置部分,以设置一个简单的应用程序来测试。

 1[label App.vue]
 2<template>
 3  <div id="app">
 4    <div>
 5      <h3>Let us test your arithmetic.</h3>
 6      <p>What is the sum of the two numbers?</p>
 7      <div class="inline">
 8        <p>{{ x1 }} + {{ x2 }} =</p> <input v-model="guess"> <button v-on:click="check">Check Answer</button>
 9      </div>
10      <button v-on:click="refresh">Refresh</button>
11      <p>{{message}}</p>
12    </div>
13  </div>
14</template>
15
16<script>
17export default {
18  name: 'App',
19  data() {
20    return {
21      x1: Math.ceil(Math.random() * 100), 
22      x2: Math.ceil(Math.random() * 100),
23      guess: "",
24      message: ""
25    }
26  },
27  methods: {
28    check() {
29      if (this.x1 + this.x2 === parseInt(this.guess)) {
30        this.message = "SUCCESS!"
31      } else {
32        this.message = "TRY AGAIN"
33      }
34    },
35    refresh() {
36      this.x1 = Math.ceil(Math.random() * 100);
37      this.x2 = Math.ceil(Math.random() * 100);
38    }
39  }
40}
41</script>
42
43<style>
44#app {
45  font-family: Avenir, Helvetica, Arial, sans-serif;
46  -webkit-font-smoothing: antialiased;
47  -moz-osx-font-smoothing: grayscale;
48  text-align: center;
49  color: #2c3e50;
50  margin-top: 60px;
51}
52.inline * {
53  display: inline-block;
54}
55img {
56  height: 350px;
57}
58</style>

这里是我们开始的app.spec.js的样子:

 1import { mount } from "@vue/test-utils";
 2import App from "./../src/App.vue";
 3
 4describe("App", () => {
 5  // Inspect the raw component options
 6  it("has data", () => {
 7    expect(typeof App.data).toBe("function");
 8  });
 9});
10
11describe("Mounted App", () => {
12  const wrapper = mount(App);
13
14  test("is a Vue instance", () => {
15    expect(wrapper.isVueInstance()).toBeTruthy();
16  });
17
18  it("renders the correct markup", () => {
19    expect(wrapper.html()).toContain(
20      "<p>What is the sum of the two numbers?</p>"
21    );
22  });
23
24  // it's also easy to check for the existence of elements
25  it("has a buttons", () => {
26    expect(wrapper.contains("button")).toBe(true);
27  });
28
29  it("renders correctly with different data", async () => {
30    wrapper.setData({ x1: 5, x2: 10 });
31    await wrapper.vm.$nextTick();
32    expect(wrapper.text()).toContain("10");
33  });
34
35  it("button click without correct sum", () => {
36    expect(wrapper.vm.message).toBe("");
37    const button = wrapper.find("button");
38    button.trigger("click");
39    expect(wrapper.vm.message).toBe("TRY AGAIN");
40  });
41
42  it("button click with correct sum", () => {
43    wrapper.setData({ guess: "15" });
44    const button = wrapper.find("button");
45    button.trigger("click");
46    expect(wrapper.vm.message).toBe("SUCCESS!");
47  });
48});

请记住,只是 Jest 中的测试的代名词,运行npm run test,所有测试都应该通过。

让我们开始 Snapshot 测试吧!

运行npm install --save-dev jest-serializer-vue然后将下面的添加到package.json

1[label package.json]
2{
3  ...
4  "jest": {
5    "snapshotSerializers": ["jest-serializer-vue"]
6  },
7  ...
8}

向第二个描述块添加一些代码。

1it('renders correctly', () => {
2  const wrapper = mount(App)
3  expect(wrapper.element).toMatchSnapshot()
4})

运行测试,并注意第一次运行测试时应该看到1 snapshot written. 注意到名为__snapshots__的目录已经在app.spec.js旁边创建。

<$>[注] 请自由查看即时截图文件,该文件具有以 .snap 扩展结束的文件;您会注意到该组件的整个模板部分已经被复制,但具有前缀 v- 的属性除外。

再次运行你的测试。

<$> [警告] 错误! <$>

为什么?!

如果您在您的终端中检查即时测试的输出,很清楚为什么:我们在我们的页面上有随机生成的数字。您还应该能够看到即时测试中的数字是什么。

它应该看起来像这样,一旦你再次通过它:

 1it('renders correctly', () => {
 2  const wrapper = mount(App, {
 3    data() {
 4      return {
 5        x1: 37,
 6        x2: 99
 7      }
 8    }
 9  })    
10  expect(wrapper.element).toMatchSnapshot()
11})

另一种方法是为我们的代码中非定义函数写一个模仿函数,在我们的例子中,那就是‘Math.random()’。

你会最终遇到一些如下的事情:

1it('renders correctly with mock', () => {
2  Math.random = jest.fn(() => .37);
3  const wrapper = mount(App)    
4  expect(wrapper.element).toMatchSnapshot()
5})

假设我们想将我们的标题移动到页面上的照片上方,这是一个简单的修改您的Vue组件,所以继续做,然后再试试测试套件。

<$> [警告] 错误! <$>

它失败了,因为我们的快照有不同的页面安排,我们必须更新我们的快照的那个部分,我们可以通过运行npm测试 - -u来做到这一点。

现在我们的测试再次过去了。

<$>[注] 成功! <$>

如果您想以交互式方式更新快照,您可以运行npm 测试 -i

结论

Snapshots 可以非常有用,以保持您的应用程序界面发生的随机变化。 Snapshots 应该像任何其他代码一样检查 Git。

Snapshot 测试应该对您在测试 Vue 应用程序时非常有用,特别是因为它们变得更加复杂。

Published At
Categories with 技术
Tagged with
comments powered by Disqus