I wonder how to test computed properties in Vue.js
's unit tests.
I have create a new project via vue-cli
(webpack
based).
For example here are my Component:
<script>
export default {
data () {
return {
source: []
}
},
methods: {
removeDuplicates (arr) {
return [...new Set(arr)]
}
},
computed: {
types () {
return this.removeDuplicates(this.source))
}
}
}
</script>
I've tried to test it like this
it('should remove duplicates from array', () => {
const arr = [1, 2, 1, 2, 3]
const result = FiltersList.computed.types()
const expectedLength = 3
expect(result).to.have.length(expectedLength)
})
QUESTION (two problems):
this.source
is undefined
. How to mock or set value to it? (FiltersList.data
is a function);removeDuplicates
method, but how to mock(stub) this call?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.
Yes, you can setup watcher on computed property, see the fiddle.
A computed property is used to declaratively describe a value that depends on other values. When you data-bind to a computed property inside the template, Vue knows when to update the DOM when any of the values depended upon by the computed property has changed.
Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time. Computed props are evaluated lazily, meaning they are only executed when they are needed to be used.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With