Vue Testing
Let's make Vue Testing And Mocking Become Easier And Much Fun.
Installation
npm install vue-testing inject-loader --save-dev
Motivation
If you're testing without vue-testing
you'll realize that you have a long boilerplate code to mock up your component. Let me show you how it looks. It's taken from https://vue-loader.vuejs.org/en/workflow/testing-with-mocks.html
<!-- example.vue --> {{ msg }}
// example.spec.js // Import the component and make the injection preparationconst ExampleInjector = // Inject and Mock External Resourceconst ExampleWithMocks =
Magic Vue Properties
Probably, you'll not get frustated with that code. Cause it's simple. until your component uses vue properties that magically injected by some plugin. For example vue-router
injects this.$router
and this.$route
Or vuex
injects this.$store
. It will throw error variable undefined since we not render the whole app. So, How do you handle it without touching your component code? It needs some effort.
<!-- example.vue --> {{ msg }}
// example.spec.js // Import the component and make the injection preparationconst ExampleInjector = // Inject and Mock External Resourceconst ExampleWithMocks = // You can inject magic properties this wayExampleWithMocks { this$route = params: {} this$router = {} }
Vuex Helper Function
Oke, let's say that you always pass the router params via props since vue-router@2.2.x
. But you'll still get the problem when you're using vuex helper function like mapActions
, mapStates
, mapGetters
. Sure, you need write more.
<!-- example.vue --> {{ msg }}
// example.spec.js // Import the component and make the injection preparationconst ExampleInjector = // Inject and Mock External Resourceconst ExampleWithMocks = // Mock The Method To Put Your SpyExampleWithMocksmethods = ...ExampleWithMocksmethods { return spy } // You can inject magic properties this wayExampleWithMocks { this$route = params: {} this$router = {} }
Let's Make It Simple!
Let's make it simple with vue-testing
. You'll just need little effort to mock your component constructor. Take a peek.
// example.spec.js // Import Vue Testing Helpers; // Import the component and make the injection preparationconst ExampleInjector = // Mock It!let Component =
Have You Tested Your Components? You Should Be~
Thank You for Making this useful~
Let's talk about some projects with me
Just Contact Me At:
- Email: bosnaufalemail@gmail.com
- Skype Id: bosnaufal254
- twitter: @BosNaufal
License
MIT Copyright (c) Naufal Rabbani