我如何从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:无法读取未定义的属性'path'”
[当我尝试使用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()。
在上面的代码中,someData
是通过属性访问器通过vue-property-decorator
定义的计算属性。
可以在类原型上的两点上进行存根:
sinon.stub(MyApp.prototype, 'someData').get(() => 'foo');
或组件选项:
sinon.stub(MyApp.options.computed.someData, 'get').value('foo');
您可以设置组件的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')
如果您只是想避免未定义$route
的错误,则可以mock $route
upon mounting:
$route