如何为单元测试桩造Vue组件方法

4

我应该如何针对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 warn]: Error in render: "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:无法存根不存在的 own 属性 someData

此外,我想为其他我想要存根的方法(例如 initSomeStringProperty())进行类似的存根操作时同样出现了相同的错误。


这是一个vue-class-component。请在上面编辑的问题中找到示例代码。 - nymvno
3个回答

1
你可以在组件挂载时设置计算属性和方法,如下所示。更新:从1.x开始,设置方法已被弃用,推荐使用存根(请参见@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')

1
通过 methods 属性覆盖方法已被弃用,并将在下一个主要版本中删除。对于 methods 属性,没有明确的迁移路径 - Vue 不支持任意替换方法,VTU 也不应该这样做。为了存根复杂的方法,请从组件中提取它并在隔离环境中进行测试。否则,建议重新考虑这些测试。 - Vongarnichts undStuff
1
@VongarnichtsundStuff 添加了有关弃用的注释。 - tony19

1
在上面的代码中,someData 是通过 vue-property-decorator 定义的属性访问器计算属性。
它可以在两个点上进行存根处理,要么在类原型上:
sinon.stub(MyApp.prototype, 'someData').get(() => 'foo');

或组件选项:
sinon.stub(MyApp.options.computed.someData, 'get').value('foo');

0
对于Vue 3,你可以在使用mountshallowMount之前对组件本身进行存根处理。
sinon.stub(YourComponentName.methods, 'yourMethodName');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接