javascript - 使用 Apollo 和 Nuxt 测试 VueJS fetch()
问题描述
我正在尝试测试async fetch()
我的 Vue 组件的功能。此方法使用一些道具来构建查询以与我们的 Apollo GQL 实例一起使用。我很难找到使用我正在使用的类似配置的示例。
最终,我很想测试完整的查询(构建它和返回数据),但是如果很难测试完整的返回数据,那么我可以通过测试返回数据的构建过程来variables
解决schema
.
// ProductList.spec.js
import { shallowMount } from '@vue/test-utils'
import ProductListing from '~/components/blocks/ProductListing.vue'
import PRODUCT_LISTING_BLOCK_QUERY from '~/queries/productListingBlock.gql'
import '@testing-library/jest-dom'
const directives = {
interpolation: () => {}
}
const mocks = {
$md: {
render: value => value
}
}
describe('ProductListing', () => {
test('fetch from apollo', () => {
const testVariables = {
maxItems: 10,
matchSkus: 'ms239,mk332,as484',
matchTags: 'tag1,tag2,tag3',
matchCategories: '111,222,333,444'
}
const wrapper = shallowMount(ProductListing, {
propsData: testVariables,
stubs: ['ProductTileList'],
directives,
mocks
})
const client = this.$apollo.provider.clients.defaultClient // get an error on this line saying $apollo is undefined
const products = await client
.query({
PRODUCT_LISTING_BLOCK_QUERY,
testVariables,
context: {
clientName: 'powerchord'
}
})
.then(r => r.data.allProducts)
// const promise = wrapper.vm.fetch() // this doesn't seem to work/call my function
})
})
// ProductList.vue
<template lang="pug">
.mb-8(:id='elementId')
ProductTileList(:products="products")
</template>
<script lang="ts">
import Vue from 'vue'
import BaseBlockMixin from './BaseBlockMixin'
import query from '~/queries/productListingBlock.gql'
import { IObjectKeys } from '~/types/common-types'
import mixins from '~/utils/typed-mixins'
const Block = Vue.extend({
props: {
matchCategories: {
type: String,
default: ''
},
matchSkus: {
type: String,
default: ''
},
matchTags: {
type: String,
default: ''
},
maxItems: {
type: Number,
default: 20
}
},
data () {
return {
products: []
}
},
async fetch () {
const client = this.$apollo.provider.clients.defaultClient
const variables: IObjectKeys = {
limit: this.maxItems
}
if (this.matchSkus.length) {
variables.skus = this.matchSkus.split(',')
}
if (this.matchTags.length) {
variables.tags = this.matchTags.split(',')
}
if (this.matchCategories.length) {
variables.categories = this.matchCategories.split(',')
.map(c => parseInt(c))
.filter(c => !isNaN(c))
}
this.products = await client
.query({
query,
variables,
context: {
clientName: 'some-company'
}
})
.then((r: any) => r.data.allProducts)
}
})
export default mixins(Block).extend(BaseBlockMixin)
</script>
解决方案
推荐阅读
- c# - 当应用程序在后台 Xamarin IOS FireBase 时推送通知
- java - 调整文本字体大小以适应 Javafx8 中的文本框
- java - Java 使用集合准备 SELECT SQL 语句
- github - 当我在google colab中导入github代码时,无法识别文件夹并且无法导入模块
- python - 我可以将值从一个 Python 文件传递到另一个文件吗?
- botframework - 通过 WebChat 以编程方式将文件发送到机器人
- javascript - 仅当您将鼠标悬停在下拉菜单上时才显示下拉菜单,否则当您将鼠标悬停在外面时隐藏下拉菜单
- python - 打印多项式,使 x 或 s 的幂按升序或降序排列
- python - 为什么两个测试运行器(nosetest/pytest vs. python setup.py test)运行不同的测试集?
- python - Matplotlib 图形图例文本添加或修改