Unit testing with Vue — Approach, tips, and tricks — Part 2

When building a web-app in Vue or any other JS Framework, it’s important to make sure Vue components work as intended throughout the many iterations a project can have. Vue.js allows a very easy and ready to go testing setup with Vue Webpack Template, which already includes a boilerplate for unit tests (using Karma and Mocha) and E2E tests (using Nightwatch). The purpose of this article is to provide different unit test examples on various domains using Karma and Mocha. But first, it’s important to understand some basic JS testing keywords.

Already know which keywords are important before writing some tests? And what about Testing Methodologies? Testing the Vue store maybe? You can check all these topics in Part 1 of this article.

Component Tests — Using Vue instance

A component has many structures that should be tested:

Components can have multiple functions that use each other as a dependency and this can turn into some complex behaviors. So, it’s important to:

When a component instance is created, a wrapper around the component instance (also named vm) is created and it provides a great API to edit props, data, and many other properties.

Be aware that avoriaz syntax (which is very similar to vue-test-utils syntax) is used in the following tests.

Testing Lifecycle Hooks

A Vue component has multiple lifecycle hooks and to test those, actions that trigger them must be done (create the instance to test beforeMount and mounted while destroying it will trigger the beforeDestroy and destroyed).

Using this component:

-- CODE language-html line-numbers--
&lt; template &gt; <br>
&nbsp;&lt; div &gt;  &lt; /div &gt; <br>
&lt; template &gt;<br>
&lt; script &gt;<br>
&nbsp;export default {<br>
 &nbsp;&nbsp; // == Lifecycle<br>
  &nbsp;&nbsp; mounted () {<br>
   &nbsp;&nbsp;&nbsp; window.addEventListener('scroll', this.handleScroll)<br>
   &nbsp;&nbsp;},<br>
   &nbsp;&nbsp;destroyed () {<br>
   &nbsp;&nbsp;&nbsp; window.removeEventListener('scroll', this.handleScroll)<br>
  &nbsp;&nbsp;},<br>
&nbsp;&nbsp;// == Methods<br>
&nbsp;&nbsp; methods: {<br>
  &nbsp;&nbsp;&nbsp; handleScroll () {<br>
  &nbsp;&nbsp;&nbsp;&nbsp;   console.log('handleScroll')<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   return<br>
  &nbsp;&nbsp;&nbsp; }<br>
&nbsp;&nbsp;  }<br>
&nbsp; }<br>
&lt; /script &gt;<br>

To check if mounted and destroyed hooks work as intended, an instance of this component should be created and destroyed. Since stub can be applied not only to the component’s instance (and therefore the component’s methods) but also to the window, it’s possible to verify if events are being handled as well.

On the test below it’s possible to see how the lifecycle hooks are tested:

-- CODE language-js line-numbers --
describe('Basic component', () => { <br>
&nbsp; describe('Lifecycle', () => {<br>
  &nbsp;&nbsp; it('Mounted', done => {<br>
   &nbsp;&nbsp;&nbsp;  const handleScrollStub = sinon.stub(BasicComponent.methods, 'handleScroll')<br>
    &nbsp;&nbsp;&nbsp; const addEventStub = sinon.stub(window, 'addEventListener')<br>
&nbsp;&nbsp;&nbsp;const wrapper = mount(BasicComponent)<br>
&nbsp;&nbsp;&nbsp;expect(addEventStub).to.be.calledWith('scroll', wrapper.vm.handleScroll)<br>
&nbsp;&nbsp;&nbsp; handleScrollStub.restore()<br>
&nbsp;&nbsp;&nbsp;     addEventStub.restore()<br>
   &nbsp;&nbsp;&nbsp;  done()<br>
  &nbsp;&nbsp; })<br>
&nbsp;&nbsp; it('Destroyed', done => {<br>
    &nbsp;&nbsp;&nbsp; const wrapper = mount(BasicComponent)<br>
   &nbsp;&nbsp;&nbsp;  const handleScrollStub = sinon.stub(wrapper.vm, 'handleScroll')<br>
    &nbsp;&nbsp;&nbsp; const removeEventStub = sinon.stub(window, 'removeEventListener')<br>
&nbsp;&nbsp;&nbsp; wrapper.destroy()<br>
&nbsp;&nbsp;&nbsp; expect(removeEventStub).to.be.calledWith('scroll', wrapper.vm.handleScroll)<br> 
&nbsp;&nbsp;&nbsp;handleScrollStub.restore()<br>
 &nbsp;&nbsp;&nbsp;    removeEventStub.restore()<br>
  &nbsp;&nbsp;&nbsp;   done()<br>
 &nbsp;&nbsp;  })<br>
&nbsp;  })<br>
})<br>

Creating spies or stubs on the component (BasicComponent — as you see in the Mounted example) instead of creating them on the instance (wrapper.vm) is useful when you want to mock / spy on a dependency that will be invoked on the instance mount lifecycles (like beforeMount or mounted).

Testing Methods

Methods should always have a clear way of being tested, either by returning a value / Promise, changing a component’s data or controlling other functions invocations. Thinking of how a function will be tested will very probably improve the code’s quality and maintainability.

Many times functions behavior changes depending on a parameter value or other function’s invocation. The context should be mocked (probably using stubs) to test all use cases.

-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div &gt; &lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
export default {<br>
 &nbsp; ...<br>
 &nbsp; data () {<br>
  &nbsp; &nbsp;  return {<br>
  &nbsp; &nbsp; &nbsp;    currentObjects: [],<br>
  &nbsp; &nbsp; &nbsp;    hasError: false<br>
  &nbsp; &nbsp;  }<br>
 &nbsp; },<br>
&nbsp;  methods: {<br>
 &nbsp; &nbsp;   getObjects () {<br>
  &nbsp; &nbsp; &nbsp;    ...<br>
 &nbsp; &nbsp;   },<br>
 &nbsp; &nbsp;   setObjects () {<br>
   &nbsp; &nbsp; &nbsp;   const objectsOnStore = this.getObjects()<br>
  &nbsp; &nbsp; &nbsp;    if(objectsOnStore) {<br>
  &nbsp; &nbsp; &nbsp; &nbsp;      this.currentObjects = objectsOnStore<br>
  &nbsp; &nbsp; &nbsp; &nbsp;      return true<br>
  &nbsp; &nbsp; &nbsp;    } else {<br>
    &nbsp; &nbsp; &nbsp;  &nbsp;   this.hasError = true<br>
    &nbsp; &nbsp; &nbsp;  &nbsp;   return false<br>
  &nbsp; &nbsp;  &nbsp;   }<br>
 &nbsp; &nbsp;   }<br>
&nbsp;  }<br>
}<br>
&lt; /script &gt; <br>

In the above scenario, setObjectsfunction will have a behavior depending on getObjects result. In order to test both use cases, the return value of getObjects invocation should be controlled as seen in this test:

-- CODE language-js line-numbers --
describe('Objects component', () => { <br>
 &nbsp;describe('Methods', () => {<br>
  &nbsp;&nbsp; it('getObjects - should return true and set the data.currentObjects if getObjects retrieves an array of objects', done => {<br>
    &nbsp;&nbsp;&nbsp; const mockedObjects = [<br>
       &nbsp;&nbsp;&nbsp;&nbsp;{ id: 1 },<br>
      &nbsp;&nbsp;&nbsp;&nbsp; { id: 2 }<br>
     &nbsp;&nbsp;&nbsp;]<br>const wrapper = mount(ObjectsComponent) <br>
    &nbsp;&nbsp;&nbsp; const getObjectsStub = sinon.stub(wrapper.vm, 'getObjects').returns(mockedObjects)<br>
&nbsp;&nbsp;&nbsp;const result =  wrapper.vm.getObjects()<br>
&nbsp;&nbsp;&nbsp;expect(result).to.be.true<br>
&nbsp;&nbsp;&nbsp;expect(wrapper.data().currentObjects).to.be.deep.equal(mockedObjects)<br>
&nbsp;&nbsp;&nbsp;getObjectsStub.restore()<br>
   &nbsp;&nbsp;&nbsp;  done()<br>
 &nbsp;&nbsp;  })<br>
&nbsp;&nbsp;it('getObjects - should return false and set the data.hasError to true if getObjects retrieves an empty array', done => {<br>
  &nbsp;&nbsp;&nbsp;   const mockedObjects = []<br>
    &nbsp;&nbsp;&nbsp; const wrapper = mount(ObjectsComponent) <br>
     &nbsp;&nbsp;&nbsp;const getObjectsStub = sinon.stub(wrapper.vm, 'getObjects').returns(mockedObjects)<br>
     &nbsp;&nbsp;&nbsp;const result =  wrapper.vm.getObjects()<br>
    &nbsp;&nbsp;&nbsp; expect(result).to.be.false<br>
    &nbsp;&nbsp;&nbsp; expect(wrapper.data().hasError).to.be.true<br>
    &nbsp;&nbsp;&nbsp; getObjectsStub.restore()<br>
    &nbsp;&nbsp;&nbsp; done()<br>
  &nbsp;&nbsp; })<br>
&nbsp; })<br>
})<br>

When using a function that depends on an API call, an approach to take is to use a Promise. In this scenarios, the best way to proceed is to return the Promise.

The following component is connected to store. The store should be completely mocked in order to control the test’s context and avoid any kind of errors.

-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div &gt; &lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
import { GET_OBJECTS } from 'services/constants/action-types'<br>
export default {<br>
&nbsp; ...<br>
 &nbsp;data () {<br>
&nbsp;&nbsp;   return {<br>
  &nbsp;&nbsp;&nbsp;   currentObjects: []<br>
 &nbsp;&nbsp;  }<br>
&nbsp; },<br>
&nbsp; methods: {<br>
 &nbsp;&nbsp;  ...mapActions('objects', {<br>
  &nbsp;&nbsp;&nbsp;   getObjectsAction: GET_OBJECTS<br>
  &nbsp;&nbsp; }),<br>
 &nbsp; &nbsp; setObjects () {<br>
     &nbsp;&nbsp;&nbsp;return this.getObjectsAction()<br>
      &nbsp;&nbsp;&nbsp;&nbsp; .then((response) => {<br>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   this.currentObjects = response<br>
   &nbsp;&nbsp;&nbsp;&nbsp;    })<br>
  &nbsp;&nbsp;&nbsp; }<br>
&nbsp;&nbsp;  }<br>
&nbsp;}<br>
&lt; /script &gt; <br>

Returning the Promise allows the API call to be stubbed and this way, it triggers the Promise’s resolve. All the assertions should run on the callback.

Considering that getObjectsAction returns a Promise (that will perform the API request on the action), a good way to test this function would be:

--CODE language-js line-numbers --
import { GET_OBJECTS } from 'services/constants/action-types'<br>
describe('Objects component', () => {<br>
&nbsp;  let store<br>
 &nbsp;let state<br>
 &nbsp;let actions<br>
beforeEach(() => {<br>
 &nbsp;  actions = {}<br>
 &nbsp;  actions[GET_OBJECTS] = sinon.stub()<br>
&nbsp;state = {<br>
   &nbsp;&nbsp;  modules: {<br>
    &nbsp;&nbsp;   // mock state, with actions and getters if any<br>
     &nbsp;&nbsp;  objects: {<br>
     &nbsp;&nbsp;&nbsp;    namespaced: true,<br>
       &nbsp;&nbsp;&nbsp;  state: {<br>
       &nbsp;&nbsp;&nbsp;&nbsp;    objs: []<br>
       &nbsp;&nbsp;&nbsp;  },<br>
       &nbsp;&nbsp;&nbsp;  actions<br>
      &nbsp;&nbsp; }<br>
    &nbsp; }<br>
  &nbsp; }<br>
&nbsp;store = new Vuex.Store(state)<br>
 })<br>
describe('Methods', () => {<br>
&nbsp;   it('getObjects - should set data.currentObjects with response returned from getObjects', done => {<br>
    &nbsp;&nbsp; const mockedObjects = [<br>
  &nbsp;&nbsp;&nbsp;     { id: 1 },<br>
   &nbsp;&nbsp;&nbsp;    { id: 2 }<br>
  &nbsp;&nbsp;   ]<br>
&nbsp;&nbsp;const wrapper = shallow(ObjectsComponent, {<br>
&nbsp;&nbsp;&nbsp;       store<br>
 &nbsp;&nbsp;    })<br>
&nbsp;&nbsp;const getObjectsStub = sinon.stub(wrapper.vm, 'getObjects').returns(mockedObjects)<br>
&nbsp;&nbsp;wrapper.vm.getObjects()<br>
&nbsp;&nbsp;&nbsp;       .then((result) => {<br>
 &nbsp;&nbsp;&nbsp;        expect(result).to.be.true<br>
  &nbsp;&nbsp;&nbsp;       expect(wrapper.data().currentObjects).to.be.deep.equal(mockedObjects)<br>
&nbsp;&nbsp;&nbsp;getObjectsStub.restore()<br>
 &nbsp;&nbsp;&nbsp;        done()<br>
  &nbsp;&nbsp;     })<br>
  &nbsp; })<br>
&nbsp; })<br>
})

This approach (returning a Promise or a chain of Promises) is very useful in scenarios where requests need to be mocked to avoid timeout errors and allowing to test how a function will perform after the Promise’s resolve. Instead of resolving the Promise, reject it will also trigger the catch scenario on the test.

Testing Watchers

A watcher is used to react to data changes and it can be applied to a component’s props or data. To trigger watchers on the test, setData or setProps methods can be used.

-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div &gt; &lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
export default { <br>
&nbsp; props: {<br>
 &nbsp;&nbsp;  propId: {<br>
 &nbsp;&nbsp;&nbsp;    type: Number,<br>
 &nbsp;&nbsp;&nbsp;    required: true<br>
 &nbsp;&nbsp;  }<br>
&nbsp;  },<br>
&nbsp; methods: {<br>
  &nbsp;&nbsp; consoleLogValue(value) {<br>
   &nbsp;&nbsp;&nbsp;  console.log(value)<br>
  &nbsp;&nbsp; }<br>
&nbsp; },<br>
&nbsp;  watch: {<br>
  &nbsp;&nbsp; propId (newVal) {<br>
  &nbsp;&nbsp;&nbsp;   this.consoleLogValue(newVal)<br>
  &nbsp;&nbsp; }<br>
 &nbsp;},<br>
}<br>
&lt; /script &gt; <br>

Changing propId will trigger the watcher.

This test will only check if consoleLogValue is being invoked with the correct parameter using calledWith as there is no intention to verify how consoleLogValue behaves. That should be done in another test. For this reason, a stub is applied to consoleLogValue.

-- CODE language-js line-numbers --
describe('Watcher component', () => { <br>
&nbsp; let props<br>
&nbsp; beforeEach(() => {<br>
 &nbsp;&nbsp;  props = {<br>
   &nbsp;&nbsp;&nbsp;  propId: 1<br>
  &nbsp;&nbsp; }<br>
&nbsp; })<br>
&nbsp; describe('Watcher', () => {<br>
 &nbsp;&nbsp;  it('propId', done => { <br>
  &nbsp;&nbsp;&nbsp;   const wrapper = shallow(WatcherComponent, {<br>
   &nbsp;&nbsp;&nbsp;&nbsp;    propsData: props<br>
   &nbsp;&nbsp;&nbsp;  })<br>
   &nbsp;&nbsp;&nbsp;const consoleLogValueStub = sinon.stub(wrapper.vm, 'consoleLogValue')<br>
&nbsp;&nbsp;&nbsp;wrapper.setProps({<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   propId: 2<br>
   &nbsp;&nbsp;&nbsp;&nbsp;  })<br>
 &nbsp;&nbsp;&nbsp;expect(consoleLogValueStub).to.be.calledWith(2)<br>
 &nbsp;&nbsp;&nbsp;    consoleLogValueStub.restore()<br>
 &nbsp;&nbsp;&nbsp;    done() <br>
&nbsp;&nbsp;   })<br>
&nbsp; })<br>
})<br>

Testing computed properties

It’s usual to use computed properties to retrieve a value depending on one or multiple props. Computed properties usually represent simple operations that shouldn’t be placed on the template to be easier to maintain.

-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div :class="themeDiv" &gt; &lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
export default { <br>
 &nbsp;props: {<br>
 &nbsp;&nbsp;  plan: {<br>
   &nbsp;&nbsp;&nbsp;  required: true,<br>
   &nbsp;&nbsp;&nbsp;  type: String<br>
  &nbsp;&nbsp; }<br>
 &nbsp;},<br>
 &nbsp;computed: {<br>
  &nbsp;&nbsp; themeDiv: function () {<br>
  &nbsp;&nbsp;&nbsp;   if (this.plan === 'pro') {<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   return 'blue'<br>
    &nbsp;&nbsp;&nbsp; } else if (this.plan === 'trial') {<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   return 'soft-blue'<br>
    &nbsp;&nbsp;&nbsp; } else {<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   return 'orange'<br>
  &nbsp;&nbsp;&nbsp;   }<br>
  &nbsp;&nbsp; }<br>
&nbsp; }<br>
}<br>
&lt; /script &gt; <br>

To access computed properties, we can use the component instance directly (wrapper.vm.computedProperty). That said, setProps can be used to test all the branches:

<p>-- CODE language-js line-numbers --
describe('Computed component', () => { <br>
 &nbsp;let props<br>

&nbsp; beforeEach(() => {<br>
 &nbsp;&nbsp;  props = {<br>
  &nbsp;&nbsp;&nbsp;   plan: 'pro'<br>
 &nbsp;&nbsp;  }<br>
&nbsp; })<br>

&nbsp; describe('Computed', () => {<br>
  &nbsp;&nbsp; it('themeDiv', done => { <br>
  &nbsp;&nbsp;&nbsp;   const wrapper = shallow(ComputedComponent, {<br>
   &nbsp;&nbsp;&nbsp;&nbsp;    propsData: props<br>
   &nbsp;&nbsp;&nbsp;  })<br>
    &nbsp;&nbsp;&nbsp; expect(wrapper.vm.themeDiv).to.equal('blue')<br>

    &nbsp;&nbsp;&nbsp; wrapper.setProps({<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   theme: 'trial'<br>
    &nbsp;&nbsp;&nbsp; })<br>
    &nbsp;&nbsp;&nbsp; expect(wrapper.vm.themeDiv).to.equal('soft-blue')<br>

     &nbsp;&nbsp;&nbsp;wrapper.setProps({<br>
      &nbsp;&nbsp;&nbsp;&nbsp; theme: 'standard'<br>
     &nbsp;&nbsp;&nbsp;})<br>
    &nbsp;&nbsp;&nbsp; expect(wrapper.vm.themeDiv).to.equal('orange')<br>

     &nbsp;&nbsp;&nbsp;done()<br>
   &nbsp;&nbsp;})<br>
&nbsp;})<br>
}) </p>

Component Tests — Using the Object

As explained before, Vue components’ attributes are all functions. This mindset will make it easier to approach the tests we only need to know how is the object composed. Other than that we’re just testing a function, a small unit of code that shouldn’t have many dependencies.

Considering the following component:

<p>-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div :class="getClasses" &gt; <br>
&nbsp;Another component, another test, random probability<br>
&lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
export default {<br>
  &nbsp; props: {<br>
   &nbsp;&nbsp;  classModifiers: {<br>
     &nbsp;&nbsp;&nbsp;  type: Array,<br>
    &nbsp;&nbsp;&nbsp;  default: () => ['large']<br>
   &nbsp;&nbsp;  }<br>
  &nbsp; },<br>
   &nbsp;computed: {<br>
  &nbsp;&nbsp;   baseProbability () {<br>
    &nbsp;&nbsp;&nbsp;   if (this.classModifiers.includes('large')) {<br>
     &nbsp;&nbsp;&nbsp;&nbsp;    return .8<br>
     &nbsp;&nbsp;&nbsp;  }<br>

     &nbsp;&nbsp;&nbsp;  return .5<br>
    &nbsp;&nbsp; },<br>
     &nbsp;&nbsp;getClasses () {<br>
     &nbsp;&nbsp;&nbsp;  return this.classModifiers.map(function (class) {<br>
      &nbsp;&nbsp;&nbsp;&nbsp;   return `probability--${modifier}`<br>
     &nbsp;&nbsp;&nbsp;  })<br>
    &nbsp;&nbsp; }<br>
   &nbsp;},<br>
  &nbsp; methods: {<br>
     &nbsp;&nbsp;calcProbability (probMultiplier) {<br>
      &nbsp;&nbsp; &nbsp;return this.baseProbability * probMultiplier<br>
   &nbsp; &nbsp; }<br>
  &nbsp; }<br>
 }<br>
&lt; /script &gt; <br>

</p>

In order to test a function that requires values from props or from component’s data (as the Vue instance will not be created now), a variable must be created with this values and passed to the tested function. On the following tests, this variable will be named ‘context’.

<p>-- CODE language-js line-numbers --
// Working with the object here! <br>
import Probability from '../probability.vue'<br>

describe('Probability component', () => {<br>
 &nbsp;describe('Computed ', () => {<br>
 &nbsp;&nbsp; &nbsp; it('getClasses', done => {<br>
  &nbsp;&nbsp;&nbsp;  &nbsp; const context = {<br>
   &nbsp;&nbsp;&nbsp;  &nbsp;  classModifiers: ['medium', 'blue-theme', 'rounded-corners']<br>
   &nbsp;&nbsp;&nbsp;  }<br><br>

   &nbsp;&nbsp;  &nbsp;expect(Probability.computed.getClasses.call(context))<br>
   &nbsp;&nbsp;&nbsp;  &nbsp;   .to.be.eql(['probability--medium', 'probability--blue-theme', 'probability--rounded-corners'])<br>
   &nbsp;&nbsp; &nbsp;&nbsp; done()<br>
  &nbsp;&nbsp;&nbsp; })<br><br>

  &nbsp;&nbsp; it('baseProbability - should return 0.8 when "large" is on the classModifiers list', done => {<br>
    &nbsp;&nbsp;&nbsp; const context = {<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   classModifiers: ['large', 'blue-theme', 'rounded-corners']<br>
    &nbsp;&nbsp;&nbsp; }<br><br>

    &nbsp;&nbsp;&nbsp; expect(Probability.computed.baseProbability.call(context)).to.be.eq(.8)<br>
    &nbsp;&nbsp;&nbsp; done()<br>
  &nbsp;&nbsp; })<br><br>

  &nbsp;&nbsp; it('baseProbability - should return 0.5 when "large" is not on the classModifiers list', done => {<br>
   &nbsp;&nbsp;&nbsp;  const context = {<br>
    &nbsp;&nbsp;&nbsp;&nbsp;   classModifiers: ['medium', 'blue-theme', 'rounded-corners']<br>
   &nbsp;&nbsp;&nbsp;  }<br><br>

   &nbsp;&nbsp;&nbsp;  expect(Probability.computed.baseProbability.call(context)).to.be.eq(.5)<br>
   &nbsp;&nbsp;&nbsp;  done()<br>
  &nbsp;&nbsp; })<br>
&nbsp; })<br><br>

&nbsp;  describe('Methods ', () => {<br>
&nbsp;&nbsp;   it('calcProbability', done => {<br>
  &nbsp;&nbsp;&nbsp;   const context = {<br>
  &nbsp;&nbsp;&nbsp;     baseProbability: .5<br>
 &nbsp;&nbsp;    }<br><br>

 &nbsp;&nbsp;    expect(Loading.methods.calcProbability.call(context, 100)).to.be.eq(50)<br>
  &nbsp;&nbsp;   done()<br>
 &nbsp;  })<br>
 })<br>
})
</p>

Without a Vue instance, invoking functions uses the object’s properties (Object.computed, Object.methods, etc). The ‘context’ variable allows the tested function to still use the expected values from the Vue instance data structure.

The lifecycles hooks can also be invoked using the object’s properties. Operations like using functions created on mapActions can be placed on the ‘context’ variable to avoid mocking the store (one of this approach’s major advantages). Using the following component:

<p>-- CODE language-js line-numbers --
&lt; template &gt; <br>
&nbsp; &lt; div  &gt; <br>
&nbsp;Lifecycle using object example<br>
&lt; /div &gt; <br>
&lt; /template &gt; <br>
&lt; script type="text/javascript" &gt; <br>
import { mapActions } from 'vuex'<br>
 import { actionTypes } from 'services/constants'<br><br>

 export default {<br>
  &nbsp;  methods: {<br>
    &nbsp; &nbsp;  ...mapActions('app', {<br>
    &nbsp; &nbsp; &nbsp;    getInitialConfig: actionTypes.APP_GET_CONFIG<br>
    &nbsp; &nbsp;  })<br>
  &nbsp;  },<br>
  &nbsp;  created () {<br>
   &nbsp; &nbsp;   this.getInitialConfig()<br>
  &nbsp;  }<br>
 }<br>
&lt; /script &gt; <br>
</p>

The getInitialConfig function will be placed inside the ‘context’ variable and therefore, a spy is created to understand if the function is called when the created hook is invoked.

<p>-- CODE language-js line-numbers --
import Obj from '../Obj.vue'<br>

describe('Obj', () => {<br>
 &nbsp; describe('Lifecycle', () => {<br>
  &nbsp; &nbsp;  it('created', done => {<br>
   &nbsp; &nbsp; &nbsp;   const context = {<br>
    &nbsp; &nbsp; &nbsp; &nbsp;    getInitialConfig: () => {}<br>
    &nbsp; &nbsp; &nbsp;  }<br>

   &nbsp; &nbsp; &nbsp;   const getInitialConfigSpy = sinon.spy(context, 'getInitialConfigSpy')<br>
   &nbsp; &nbsp; &nbsp;   Obj.created.call(context)<br>

  &nbsp; &nbsp; &nbsp;    expect(getInitialConfigSpy).to.be.calledOnce<br>

    &nbsp; &nbsp; &nbsp;  getInitialConfigSpy.restore()<br>
  &nbsp; &nbsp; &nbsp;    done()<br>
 &nbsp; &nbsp;   })<br>
&nbsp;  })<br>
})<br>
</p>

Conclusion

Unit testing can sometimes be tricky and if you’re starting, it will surely cause some pain. But in the end, it’s worth it. If you’re still wondering about the importance of testing your Vue app, check this article.

Tests bring great advantages to the project and to the developer’s evolution. The developer’s mindset will change to write better, easier to test and more maintainable code using pure functions, following the Do One Thing (DOT) rule instead of overloading a unit of code with multiple responsibilities and taking better decisions over the structure and scalability of an application.

This article focused on showing some examples of how to approach various Vue.js testing domains, more like an easy to remind / understand how to approach a certain scenario and to help you all understand what it’s being done when writing a test. If any particularly useful scenario was skipped or if you have any suggestion, leave a comment below. Any feedback will be appreciated and don’t forget to 👏 if this article helped you!

Bruno Teixeira
Head of Product