我在我的应用程序中使用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吗?谢谢!
发布于 2021-02-20 19:51:54
我将模拟 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 })
})
})
https://stackoverflow.com/questions/66237441
复制相似问题