跳至内容

测试

过时

本指南已过时,需要针对 Vue 3 和 vue-apollo 4 进行重写。欢迎贡献!

要为 vue-apollo 查询和变异创建单元测试,您可以选择简单的测试或使用模拟的 GraqhQL 架构进行测试。这里的所有示例都使用 Jestvue-test-utils

简单测试

对于简单的查询测试,您只需设置组件数据并检查组件使用 Jest 快照功能如何呈现。例如,如果您有一个查询来显示所有 Vue 英雄,您可以添加一个包含单个英雄的模拟数组

js
test('displayed heroes correctly with query data', () => {
  const wrapper = shallowMount(App, { localVue })
  wrapper.setData({
    allHeroes: [
      {
        id: 'some-id',
        name: 'Evan You',
        image: 'https://pbs.twimg.com/profile_images/888432310504370176/mhoGA4uj_400x400.jpg',
        twitter: 'youyuxi',
        github: 'yyx990803',
      },
    ],
  })
  expect(wrapper.element).toMatchSnapshot()
})

对于简单的变异测试,您需要检查组件中是否调用了 $apollo 方法 mutate。在下面的示例中,变异是在 addHero 方法中调用的

js
test('called Apollo mutation in addHero() method', () => {
  const mutate = jest.fn()
  const wrapper = mount(App, {
    localVue,
    mocks: {
      $apollo: {
        mutate,
      },
    },
  })
  wrapper.vm.addHero()
  expect(mutate).toBeCalled()
})

使用模拟的 GraqhQL 架构进行测试

您还可以使用 模拟的 GraphQL 架构 进行更深入和更复杂的测试。此方法不包括 Apollo,但允许您检查给定架构是否会正确执行特定查询。

为此,首先您需要架构

js
const sourceSchema = `
  type VueHero {
    id: ID!
    name: String!
    image: String
    github: String
    twitter: String
  }

  input HeroInput {
    name: String!
    image: String
    github: String
    twitter: String
  }


  type Query {
    allHeroes: [VueHero]
  }

  type Mutation {
    addHero(hero: HeroInput!): VueHero!
    deleteHero(name: String!): Boolean
  } 
`

下一步是使用 graphql-tools 方法创建一个可执行的架构

js
import { makeExecutableSchema } from 'graphql-tools'
...
const schema = makeExecutableSchema({
  typeDefs: sourceSchema,
})

之后,您需要向架构添加模拟函数

js
import { addMockFunctionsToSchema } from 'graphql-tools'
...
addMockFunctionsToSchema({
  schema,
})

指定 GraphQL 查询字符串

js
const query = `
  query {
    allHeroes {
      id
      name
      twitter
      github
      image
    }
  }
`

在测试用例中调用 GraphQL 查询,将响应保存到组件数据中,然后检查呈现的组件是否与快照匹配

js
graphql(schema, query).then(result => {
  wrapper.setData(result.data)
  expect(wrapper.element).toMatchSnapshot()
})

在这种情况下,所有字符串字段将等于 Hello World,所有数字值将为负数。如果您想要更真实的响应,您应该为特定查询指定解析器

js
const resolvers = {
  Query: {
    allHeroes: () => [
      {
        id: '-pBE1JAyz',
        name: 'Evan You',
        image:
          'https://pbs.twimg.com/profile_images/888432310504370176/mhoGA4uj_400x400.jpg',
        twitter: 'youyuxi',
        github: 'yyx990803',
      },
    ],
  },
}

然后,您需要将解析器添加到可执行的架构中,并在添加模拟函数时将 preserveResolvers 属性设置为 true

js
const schema = makeExecutableSchema({
  typeDefs: sourceSchema,
  resolvers,
})

addMockFunctionsToSchema({
  schema,
  preserveResolvers: true,
})

您可以用相同的方式测试变异。