Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub Vue component methods for unit testing

How can I stub certain methods (getters, in particular) from Vue single file components for unit testing with mocha/expect?

The problem I was facing was the following: I have a component with a get method someData

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import SomeService from '@/services/some.service'

@Component()
export default class MyApp extends Vue {
    ...

    mounted () {
      ...
    }

    get someData () {
      return this.$route.path.split('/')[1] || 'main'
    }

    get getLocation () {
      return this.someService.getBaseURL()
    }

    initSomeStringProperty (): string {
      return 'some string'
    }
}
</script>

My tests always fail with:

[Vue warn]: Error in render: "TypeError: Cannot read property 'path' of undefined"

When I try to stub the method using sinon, like following:

describe('MyApp.vue', () => {
  if('returns main', () => {
    const dataStub = sinon.stub(MyApp, 'someData')
    listStub.yields(undefined, 'main')
    const wrapper = shallowMount(AppNavBar)
    expect(wrapper.text()).to.include('Some Content')
  })
})

However, I get the following error:

TypeError: Cannot stub non-existent own property someData

In addition, I get the same error for every other method, I want to stub analogously, e.g., initSomeStringProperty().

like image 862
nymvno Avatar asked Oct 27 '25 16:10

nymvno


1 Answers

In the code above someData is computed property that is defined with property accessor through vue-property-decorator.

It can be stubbed at two points, either on class prototype:

sinon.stub(MyApp.prototype, 'someData').get(() => 'foo');

Or component options:

sinon.stub(MyApp.options.computed.someData, 'get').value('foo');
like image 92
Estus Flask Avatar answered Oct 30 '25 09:10

Estus Flask