How to test computed properties in Vue.js? Can't mock "data"
Okay. I've found a dumb solution. Dumb but works.
You have been warned =)
The idea: To use .call({})
to replace this
inside that calls:
it('should remove duplicates from array', () => { const mockSource = { source: [1, 2, 1, 2, 3], getUniq (arr) { return FiltersList.methods.removeDuplicates(arr) } } const result = FiltersList.computed.types.call(mockSource) const expectedLength = 3 expect(result).to.have.length(expectedLength)})
So basically you can specify your own this
with any kind of data.and call YourComponent.computed.foo.call(mockSource)
. Same for methods
Just change the variable from which depends computed property and expect it.
This is my work example for component computed prop:
import Vue from 'vue'import Zoom from 'src/components/Zoom'import $ from 'jquery'/* eslint-disable no-unused-vars *//** * get template for wrapper Vue object make Vue with Zoom component and that template * @param wrapperTemplate * @returns {Vue$2} */const makeWrapper = (wrapperTemplate = '<div><zoom ref="component"></zoom></div>') => { return new Vue({ template: wrapperTemplate, components: {Zoom} })}const startWrapperWidth = 1093const startWrapperHeight = 289const startImageWidth = 1696const startImageHeight = 949const padding = 15/** * gets vueWrapper and return component from it * @param vueWrapper * @param useOffset * @returns {'Zoom component'} */const setSizesForComponent = (vueWrapper) => { vueWrapper.$mount() var cmp = vueWrapper.$refs.component var $elWrapper = $(cmp.$el) var $elImage = $elWrapper.find(cmp.selectors.image) $elWrapper.width(startWrapperWidth) $elWrapper.height(startWrapperHeight) $elWrapper.css({padding: padding}) $elImage.width(startImageWidth) $elImage.height(startImageHeight) cmp.calculateSizesAndProportions() return cmp}describe('onZoom method (run on mousemove)', () => { sinon.spy(Zoom.methods, 'onZoom') let vueWrapper = makeWrapper() let cmp = setSizesForComponent(vueWrapper) let e = document.createEvent('HTMLEvents') e.initEvent('mousemove', true, true) e.pageX = 150 e.pageY = 250 let callsOnZoomBeforeMousemove = Zoom.methods.onZoom.callCount cmp.$el.dispatchEvent(e) describe('left and top computed props', () => { it('left', () => { expect(cmp.left).is.equal(-74) }) it('top', () => { expect(cmp.top).is.equal(-536) }) })})