vue jest 测试_Vue.js中的Jest快照测试简介

vue jest 测试

Snapshot testing is a type of testing in Jest which monitors regression in your code and also serves as an integration test. The first means that if you add more code to your project and something small breaks, snapshot testing can catch it. The second means that snapshot testing is a way of making sure an entire component runs the way you intend it to.

快照测试是Jest中的一种测试,它监视代码中的回归并用作集成测试。 第一种意味着,如果您向项目中添加更多代码并且出现一些小中断,则快照测试可以捕获该代码。 第二个意思是快照测试是确保整个组件按预期方式运行的一种方式。

The way snapshot testing works is that the very first time you run jest, snapshots are generated of the DOM. On subsequent runs of your test suite, the DOM that’s constructed gets compared to these snapshots. Since you may have changed your code, your snapshots still matching the ones generated the first time tells you things are still working.

快照测试的工作方式是,第一次运行jest ,将为DOM生成快照。 在测试套件的后续运行中,将构建的DOM与这些快照进行比较。 由于您可能已经更改了代码,因此快照仍与第一次生成的快照相匹配,这表明您仍在工作。

Some questions naturally come up: what if I make a significant change to your program which results in different DOM contents? Jest allows you to generate new snapshots and such a scenario would warrant that. What if there is non-deterministic content on my page? There are multiple ways to handle this, and we’ll see this shortly!

自然会出现一些问题:如果我对您的程序进行了重大更改而导致不同的DOM内容该怎么办? Jest允许您生成新的快照,这种情况可以保证。 如果我的页面上有不确定的内容怎么办? 有多种处理方法,我们很快就会看到!

应用程式设定 (App Setup)

We’ll now setup our application. Head over to the setup section of our tutorial on testing Vue using Jest for setting up a simple app for testing. Here’s what your App.vue file could look like:

现在,我们将设置我们的应用程序。 转到本教程的有关使用Jest测试Vue教程的设置部分,以设置用于测试的简单应用程序。 这是您的App.vue文件的外观:

App.vue
应用程序
<template>
  <div id="app">
    <div>
      <h3>Let us test your arithmetic.</h3>
      <p>What is the sum of the two numbers?</p>
      <div class="inline">
        <p>{{ x1 }} + {{ x2 }} =</p> <input v-model="guess"> <button v-on:click="check">Check Answer</button>
      </div>
      <button v-on:click="refresh">Refresh</button>
      <p>{{message}}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      x1: Math.ceil(Math.random() * 100), 
      x2: Math.ceil(Math.random() * 100),
      guess: "",
      message: ""
    }
  },
  methods: {
    check() {
      if (this.x1 + this.x2 === parseInt(this.guess)) {
        this.message = "SUCCESS!"
      } else {
        this.message = "TRY AGAIN"
      }
    },
    refresh() {
      this.x1 = Math.ceil(Math.random() * 100);
      this.x2 = Math.ceil(Math.random() * 100);
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.inline * {
  display: inline-block;
}
img {
  height: 350px;
}
</style>

And here’s what our started app.spec.js looks like:

这是我们启动的app.spec.js样子:

import { mount } from "@vue/test-utils";
import App from "./../src/App.vue";

describe("App", () => {
  // Inspect the raw component options
  it("has data", () => {
    expect(typeof App.data).toBe("function");
  });
});

describe("Mounted App", () => {
  const wrapper = mount(App);

  test("is a Vue instance", () => {
    expect(wrapper.isVueInstance()).toBeTruthy();
  });

  it("renders the correct markup", () => {
    expect(wrapper.html()).toContain(
      "<p>What is the sum of the two numbers?</p>"
    );
  });

  // it's also easy to check for the existence of elements
  it("has a buttons", () => {
    expect(wrapper.contains("button")).toBe(true);
  });

  it("renders correctly with different data", async () => {
    wrapper.setData({ x1: 5, x2: 10 });
    await wrapper.vm.$nextTick();
    expect(wrapper.text()).toContain("10");
  });

  it("button click without correct sum", () => {
    expect(wrapper.vm.message).toBe("");
    const button = wrapper.find("button");
    button.trigger("click");
    expect(wrapper.vm.message).toBe("TRY AGAIN");
  });

  it("button click with correct sum", () => {
    wrapper.setData({ guess: "15" });
    const button = wrapper.find("button");
    button.trigger("click");
    expect(wrapper.vm.message).toBe("SUCCESS!");
  });
});

Keep in mind that it is just an alias for test in Jest. Run npm run test and all tests should pass.

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

让我们开始快照测试! (Let’s Start Snapshot Testing!)

Run npm install --save-dev jest-serializer-vue then make the below addition to package.json

运行npm install --save-dev jest-serializer-vue然后在package.json中添加以下内容

package.json
package.json
{
  ...
  "jest": {
    "snapshotSerializers": ["jest-serializer-vue"]
  },
  ...
}

Add some code to the second describe block.

在第二个describe块中添加一些代码。

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

Run your tests and notice how the first time you run your tests you should see “1 snapshot written”. Notice that a directory called __snapshots__ has been created next to app.spec.js.

运行测试,并注意第一次运行测试时,应该看到“已编写1个快照”。 请注意,目录名为__snapshots__已创建旁边app.spec.js

Feel free to take a look at the snapshot file, which has a file ending with the .snap extension; you’ll notice that the whole template section of the component has been reproduced, except for attributes that have the prefix v-.

随时查看快照文件,该文件的扩展名为.snap 。 您会注意到,该组件的整个模板部分均已复制,但带有前缀v-属性除外。

Run your tests again.

再次运行测试。

Error!

错误!

Why?!

为什么?!

If you examine the snapshot test’s output in your Terminal, it’s clear why: we have randomly generated numbers on our page. You should also be able to see what the numbers in the snapshot are. Go ahead and substitute those into your test by passing data when you mount your component; the function you pass will be merged into the component’s own data.

如果您在终端中检查快照测试的输出,则很清楚原因:我们在页面上随机生成了数字。 您还应该能够看到快照中的数字。 继续,并在安装组件时通过传递data将其替换为测试中的内容; 您传递的函数将合并到组件自己的data

It should look something like this once you have it passing again:

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

it('renders correctly', () => {
  const wrapper = mount(App, {
    data() {
      return {
        x1: 37,
        x2: 99
      }
    }
  })    
  expect(wrapper.element).toMatchSnapshot()
})

Another approach is to write a mock function for the nondeterministic function in our code. In our case that is Math.random().

另一种方法是在我们的代码中为非确定性函数编写一个模拟函数。 在我们的例子中是Math.random()

You’d wind up with the something like the following:

您将得到如下所示的结果:

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

Let’s say we wanted to move our header to be above the photo on the page. This is an easy modification to your Vue component so go ahead and do that. Try running your test suite again.

假设我们想将标题移动到页面照片上方。 这是对Vue组件的简单修改,因此继续进行。 尝试再次运行测试套件。

Error!

错误!

It failed because our snapshot has the page arranged differently. We must update that part of our snapshot and we can do that by running npm test -- -u.

失败是因为我们的快照页面的排列方式不同。 我们必须更新快照的该部分,然后可以通过运行npm test -- -u来做到这一点。

Now our tests pass again.

现在我们的测试又通过了。

Success!

成功!

If you wanted to update snapshots interactively, you can run npm test -- -i.

如果要交互式更新快照,则可以运行npm test -- -i

结论 (Conclusion)

Snapshots can be very useful in keeping abreast of any accidental changes to your application’s interface. Snapshots should be checked into Git like any other code. If tests fail, check what has happened before reflexively updating your snapshots.

快照对于及时了解应用程序界面的任何意外更改非常有用。 快照应像其他任何代码一样签入Git。 如果测试失败,请自发更新快照之前检查发生了什么。

Snapshot testing should be very useful to you in testing your Vue applications, especially as they get more complex. Good luck out there!

快照测试对您测试Vue应用程序非常有用,尤其是当它们变得更加复杂时。 祝你好运!

翻译自: https://www.digitalocean.com/community/tutorials/vuejs-jest-snapshot-testing-in-vue

vue jest 测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值