首页 > 解决方案 > 使用 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>

标签: javascriptvue.jsunit-testingnuxt.jsapollo

解决方案


推荐阅读