Programatt
Programatt

Reputation: 836

Testing Methods within Vue Components using Jasmine

I have the following test which works great

  it('does not render chapter div or error div', () => {
        const payLoad =  chapter;
        const switcher = 'guild';
        var vm = getComponent(payLoad, switcher).$mount();
        expect(vm.$el.querySelector('#chapter-card')).toBeNull();
        expect(vm.$el.querySelector('#error-card')).toBeNull();

    });

To do this I wrote a helper method that mounts a component:

  const getComponent = (prop1) => {
        let vm = new Vue({
            template: '<div><compd :payLoad="group" :index="index" "></compd ></div></div>',
            components: {
                compd,
            },
            data: {
                payLoad: prop1,
                
            },

        })
        return vm;
    }

however, I have a method within my vue component compd. For simplicitys sake, lets call it

add(num,num){
return num+num;
}

I want to be able to write a test case similar to the following:

  it('checks the add method works', () => {
       
        expect(compd.add(1,2).toBe(3));

    });

I cannot figure out how to do this. Has anyone any suggestions? The documentation here: https://v2.vuejs.org/v2/guide/unit-testing.html Does not cover testing methods.

Upvotes: 3

Views: 2917

Answers (1)

Cristi Jora
Cristi Jora

Reputation: 1752

Source code from vue repo

As you can see the method gets called simply on the instance

const vm = new Vue({
  data: {
    a: 1
  },
  methods: {
    plus () {
      this.a++
    }
  }
})
vm.plus()
expect(vm.a).toBe(2)

You can also access the method via $options like in this case (vue source code)

const A = Vue.extend({
  methods: {
    a () {}
  }
})
const vm = new A({
  methods: {
    b () {}
  }
})
expect(typeof vm.$options.methods.a).toBe('function')

Update: To test child components use $children to access the necessary child. Example

var childToTest = vm.$children.find((comp)=>comp.$options.name === 'accordion')`  assuming name is set to `accordion`

After that you can

childToTest.plus();
vm.$nextTick(()=>{
  expect(childToTest.someData).toBe(someValue)
  done(); //call test done callback here
})

If you have a single child component and not a v-for put a ref on it `

vm.$refs.mycomponent.myMethod()

Upvotes: 2

Related Questions