The power of Snapshot Testing in Vue.js
如果您要进行测试,则可能使用了Jest:Facebook创建的多合一测试框架。目前,它是目前最受欢迎的工具,自从我第一次尝试以来就一直在使用它。
要测试Vue.js组件,您还可以使用Edd Yerburg编写的vue-test-utils,它是官方的帮助程序库,使测试Vue.js应用程序更加容易。
这是使用Jest和vue-test-utils进行测试的示例:
it('has a message list of 3 elements', () => {
const cmp = createCmp({ messages: ['msg-1', 'msg-2', 'msg-3'] })
expect(cmp.is('ul')).toBe(true)
expect(cmp.find('.message-list').isEmpty()).toBe(false)
expect(cmp.find('.message-list').length).toBe(3)
})
it('has a message prop rendered as a data-message attribute', () => {
const cmp = createCmp({ message: 'Cat' })
expect(cmp.contains('.message')).toBe(true)
expect(cmp.find('.message').props('message').toBe('Cat')
expect(cmp.find('.message').attributes('data-message').toBe('Cat')
// Change the prop message
cmp.setProps({ message: 'Dog' })
expect(cmp.find('.message').props('message').toBe('Dog')
expect(cmp.find('.message').attributes('data-message').toBe('Dog')
})
如您所见,vue-test-utils为您提供了许多可用于检查道具,类,内容,搜索等的方法。它为您提供了更改内容的方法,例如setProps,这非常酷。
This test has very specific assertions in the form of “Find an element with a ‘message’ class and check if it has a ‘data-message’ set to ‘Cat’”.
But what if I tell you that… you don’t need to do that with Snapshot Testing?
Basically, you can rewrite the previous tests by using snapshots in the following way:
it("has a message list of 4 elements", () => {
const cmp = createCmp({ messages: ["msg-1", "msg-2", "msg-3"] });
expect(cmp.element).toMatchSnapshot();
});
it("has a message prop rendered as a data-message attribute", () => {
const cmp = createCmp({ message: "Cat" });
expect(cmp.element).toMatchSnapshot();
cmp.setProps({ message: "Dog" });
expect(cmp.element).toMatchSnapshot();
});
The value of the tests will remain the same, or it can have even more since sometimes you find non-related regressions in snapshots.
Notice that in this test I’ve just used toMatchSnapshot for the assertions, and that’s all. That makes testing much easier and quicker since you don’t need to check every specific thing.
The dynamics of testing changed: instead of writing specific assertions, you set the component state in any way you need and take snapshots of it.
Snapshots are meant to assert the rendering state: they describe how the component is rendered given a specific state, and in later runs the snapshots are compared to check its validity.
Keep in mind that not always snapshot testing is what you need. It depends on what you need to test.
I can’t fit more in a tip, but if you want more information you have the book Testing Vue.js Components with Jest where I added last week a whole section on snapshot testing, including:
网友评论