在 Vue3 中使用 Jest 测试 ApolloClient API(组合 API)

Test ApolloClient API with Jest in Vue3 (Composition API)

我正在为我的应用程序使用 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 吗?谢谢!

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

// 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