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().
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');
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