Divyanth Jayaraj
Divyanth Jayaraj

Reputation: 960

How can I test computed properties in VueJS?

I'm using VueJS from Vue CLI. So all my components are in .vue format.

In one of my components, I have an array called fields in the data section.

//Component.vue
data() {
  return {
     fields : [{"name" : "foo", "title" : "Foosteria"}, {"name" : "bar", "title" : "Barrista"}]
  }
}

I have a computed property that is a subset of fields

//Component.vue
computed : {
    subsetOfFields () {
       // Something else in component data determines this list
    }
}

I've set up all of my unit tests in jasmine like this and they work fine.

 //Component.spec.js
 import Vue from 'vue'
 import MyComponent from 'Component.vue'
 describe("Component test", function() {
      var myComponentVar = new Vue(MyComponent);
      var vm = myComponentVar.$mount();

      beforeEach(function() {
         vm = myComponentVar.$mount();
      );

      afterEach(function() {
         vm = myComponentVar.$destroy();
      });

      it("First spec tests something", function() {
            ...
       });

 });

For everything else, doing something inside the spec, then running assertions on the data objects works just fine. However, running an assertion on subsetOfFields always returns an empty array. Why so? What should I do, in order to be able to test it?

FYI, I even tried nesting the spec inside another describe block and then adding a beforeEach which initializes the fields array. It did not work.

However, initializing fields inside the generic beforeEach function worked. But I don't want to initialize the fields array with that mock data for the other specs.

Upvotes: 13

Views: 13858

Answers (1)

JoeManFoo
JoeManFoo

Reputation: 359

I came across this link that talks about testing and the section you'll need to look at is the Vue.nextTick(...) section

https://alligator.io/vuejs/unit-testing-karma-mocha/

The block I'm talking about is below:

import Vue from 'vue';
// The path is relative to the project root.
import TestMe2 from 'src/components/TestMe2';

describe('TestMe2.vue', () => {
  ...
  it(`should update when dataText is changed.`, done => {
    const Constructor = Vue.extend(TestMe2);

    const comp = new Constructor().$mount();

    comp.dataProp = 'New Text';

    Vue.nextTick(() => {
      expect(comp.$el.textContent)
        .to.equal('New Text');
      // Since we're doing this asynchronously, we need to call done() to tell Mocha that we've finished the test.
      done();
    });
  });
});

Upvotes: 3

Related Questions