3

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.

2
  • 1
    You're missing a closing parenthesis after expect(compd.add(1,2) Commented Apr 24, 2017 at 17:10
  • It should be expect(compd.add(1,2)).toBe(3) Commented Apr 27, 2017 at 0:12

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.