如何为单元测试存根Vue组件方法

7y4bm7vi  于 7个月前  发布在  Vue.js
关注(0)|答案(3)|浏览(95)

如何从Vue单文件组件中存根某些方法(特别是getter),以便使用mocha/expect进行单元测试?
我面临的问题如下:我有一个带有get方法 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>

字符串
我的测试总是失败:
[Vue返回错误:TypeError:Cannot read property 'path' of undefined
当我尝试使用sinon来存根方法时,如下所示:

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


但是,我得到以下错误:
TypeError:无法存根不存在的自己的属性someData
此外,我对其他方法也会得到同样的错误,我想类似地存根,例如,initSomeStringProperty()。

sauutmhj

sauutmhj1#

在上面的代码中,someData是通过vue-property-decorator使用属性访问器定义的计算属性。
它可以在两个点上被存根化,要么在类原型上:

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

字符串
或组件选项:

sinon.stub(MyApp.options.computed.someData, 'get').value('foo');

relj7zay

relj7zay2#

您可以在挂载时设置组件的计算props和方法,如下所示。* 更新:自1.x起,设置方法已被弃用,转而支持batch(请参阅@EstusFlask关于如何正确使用Sinon存根的答案)。*

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

字符串
如果你只是想避免$route未定义的错误,你可以在挂载时模拟$route

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

xqk2d5yq

xqk2d5yq3#

对于Vue 3,您可以在使用mountshallowMount之前存根组件本身:

sinon.stub(YourComponentName.methods, 'yourMethodName');

字符串

相关问题