Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test computed properties in Vue.js? Can't mock "data"

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):

  1. this.source is undefined. How to mock or set value to it? (FiltersList.data is a function);
  2. Perhaps I don't wan't to call removeDuplicates method, but how to mock(stub) this call?
like image 367
Sergei Panfilov Avatar asked Jan 25 '17 17:01

Sergei Panfilov


People also ask

How do you write unit test for computed properties in Vue?

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.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

How do computed properties work in Vue?

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.

What is the difference between watchers and computed property in Vuejs?

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.


Video Answer


1 Answers

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

like image 161
Sergei Panfilov Avatar answered Sep 28 '22 11:09

Sergei Panfilov