How to stub Vue component methods for unit testing

微笑、不失礼 提交于 2020-06-17 04:12:10

问题


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


回答1:


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



回答2:


You could set the component's computed props and methods upon mounting:

const wrapper = shallowMount(MyApp, {
  computed: {
    someData: () => 'foo'
  },
  methods: {
    initSomeStringProperty: () => 'bar'
  }
})
expect(wrapper.vm.someData).to.equal('foo')
expect(wrapper.vm.initSomeStringProperty()).to.equal('bar')

If you were just trying to avoid the error about $route being undefined, you could mock $route upon mounting:

const wrapper = shallowMount(MyApp, {
  mocks: {
    $route: { path: '/home' }
  }
})
expect(wrapper.vm.someData).to.equal('home')


来源:https://stackoverflow.com/questions/60150559/how-to-stub-vue-component-methods-for-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!