首页 > 解决方案 > 测试 GraphQL Apollo 和 Vue.js

问题描述

我正在尝试对 Vue.js 和 Apollo 应用程序中的组件进行单元测试。组件的一般行为是查询服务器,将响应加载到dataVue 组件中。当按下按钮时,运行 GraphQL 突变,然后使用响应数据更新数据。这是组件的存根。

Vue.extend({
  $apollo: {
    person: {
      query: gql`query($id: ID!) {
        person(id: $id) {
          name
          id
        }
      }`,
      fetch-policy: 'network-only',
    }
  },
  data() {
    return {
      person: {},
      newPersonId: null,
    }
  },
  methods: {
    getNewPerson() {
      this.$apollo.mutate({
        mutation: gql`mutation($person: Person!) {
          savePerson(person: $Person) {
            person {
              id
            }
          }
        }`,
        update: (store, { data }) {
          ////////////////////////////
          // test-what-happens-here //
          ////////////////////////////        
        }
      })
    }
  }
});

我的直觉说要编写的适当测试是

it('renders the name in correctly on load')
it('sends the correct data with the mutation')
it('does the right thing when the server responds') <--- Most Important
it('does the right thing when the server responds with an error')  <--- Most Important

我编写了一些测试,但似乎没有一个是测试组件往返的好模式。

如果这是一个 axios 请求,我会模拟响应以发送 200 和正确的数据,并断言 axios 请求是使用正确的 JSON 调用的,并且组件看起来是正确的,基于存根响应。

我一辈子都无法用 vue-apollo 解决这个问题。

他们有一个不错的测试部分,但是使用 apollo 的“简单测试”无法测试请求的结果,而且这些graphql-tools测试实际上并没有利用 apollo,因此它错过了相当多的行为。

您将如何在上面的代码中测试更新功能?

标签: unit-testingvue.jsmockinggraphqlvue-apollo

解决方案


推荐阅读