如何解决在另一个计算属性上调用getter不是测试函数
我一直在尝试模拟getter函数,但是另一个计算属性也调用了此函数,并且该函数作为未定义的函数返回。
这是一个面包屑组件,它会根据路由路径而相应地更改。第一次测试正常通过,因为不应渲染该组件。但是第二项测试尝试使用用户名通过吸气剂获取用户数据。
我的疑问是关于模拟吸气剂。不是应该返回在beforeEach定义的模拟对象吗?
谢谢!
这是测试规格:
import {
shallowMount,createLocalVue
} from '@vue/test-utils'
import Breadcrumb from '@/components/Breadcrumb.vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VueRouter)
const router = new VueRouter()
describe('Breadcrumb.vue',() => {
let store
beforeEach(() => {
store = new Vuex.Store({
getters: {
getUserByUsername: (path) => ({
name: {
first: 'FirstName',last: 'LastName'
}
})
}
})
})
it('renders home page breadcrumb',() => {
const wrapper = shallowMount(Breadcrumb,{ store,router,localVue })
const component = wrapper.find('.breadcrumb')
expect(component.text()).toBe('')
})
it('renders users page breadcrumb',() => {
router.push('/users')
const wrapper = shallowMount(Breadcrumb,localVue })
const component = wrapper.find('.breadcrumb')
expect(component.text()).toBe('')
})
})
第一个测试通过,但第二个返回:
TypeError: this.getUserByUsername is not a function
41 | crumbs.push(this.users)
42 | for (const path of paths) {
> 43 | const user = this.getUserByUsername(path)
| ^
44 | if (user) {
45 | crumbs.push({
46 | label: `${user.name.first} ${user.name.last}`,
这是组件的计算函数:
computed: {
...mapGetters(['getUserByUsername']),breadcrumbs () {
const crumbs = []
const routePath = this.$route.path
if (routePath === '/' || routePath === '/404') return []
const paths = routePath.split('/')
delete paths[0]
crumbs.push(this.home)
crumbs.push(this.users)
for (const path of paths) {
const user = this.getUserByUsername(path)
if (user) {
crumbs.push({
label: `${user.name.first} ${user.name.last}`,path: `/${path}`
})
}
}
return crumbs
}
}
解决方法
我怀疑您需要对此进行更改:
getUserByUsername: (path) => ({
收件人:
getUserByUsername: () => (path) => ({
从错误消息和组件代码来看,getUserByUsername
的真实版本似乎正在返回一个函数,因此模拟版本也需要这样做。查看原始getUserByUsername
进行确认。
回想一下,getter的外部函数不是您显式调用的。当您访问该属性时,该属性在幕后使用,并被传递state
作为其第一个参数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。