【问题标题】:Test ApolloClient API with Jest in Vue3 (Composition API)在 Vue 3 中使用 Jest 测试 Apollo 客户端 API(组合 API)
【发布时间】:2021-05-20 01:49:17
【问题描述】:

我在我的应用程序中使用Vue3 (typescript)Composition API。我正在使用 ApolloClient grapghql 进行 API 调用。我为 API 调用创建了一个单独的服务文件。 (PFB 文件)

服务文件

import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client/core"
import { gql } from "@apollo/client/core"
import fetch from 'cross-fetch';

const httpLink = new HttpLink({
    uri: process.env.VUE_APP_BACKEND_GRAPHQL_URI,
    fetch
})

const apolloClient = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache(),
})

export const getAplloAPIdata = async  (reqQuery: any) => {
    const query = gql `${reqQuery}`
    try {
        return await apolloClient.query({ query })
    }catch {
        console.log('API error')
    }
}

Home.vue

setup() {
    const threatList = ref([])
    const threat = ref(null)

    // get all threats
    const getThreats = async () => {
        const getThreatsQuery = `
            query {
                threats {
                    short_description
                    threat_level
                }
            }
        `

        try {
            const result = await getAplloAPIdata(getThreatsQuery)
            if (result) {
                threatList.value = result.data.threats
            }
        } catch {
            console.log('Error receiving threats data')
        }
    }

你能告诉我如何编写测试用例来开玩笑地模拟这个 API 吗?谢谢!

【问题讨论】:

    标签: jestjs graphql apollo-client vuejs3 vue-composition-api


    【解决方案1】:

    我会 mock getAplloAPIdata 返回模拟数据,并在您的测试中验证该数据。关键是要确保模拟路径与组件中导入的路径相同:

    // Home.vue
    import { getAplloAPIdata } from '@/service'
    /*...*/
    
    // Home.spec.js
    jest.mock('@/service', () => {
      return {
        getAplloAPIdata: () => ({
          data: {
            threats: [{ id: 123456 }]
          }
        })
      }
    })
    
    describe('Home.vue', () => {
      it('gets threats', async () => {
        const wrapper = shallowMount(Home)
        await wrapper.vm.getThreats()
        expect(wrapper.vm.threatList).toContainEqual({ id: 123456 })
      })
    })
    

    GitHub demo

    【讨论】:

      猜你喜欢
      • 2022-07-19
      • 2021-02-08
      • 2020-06-08
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 2021-02-27
      相关资源
      最近更新 更多