DEV Community

Cover image for Testing Apollos reactive variables in Vuejs and GraphQL
Austin Vance for Focused

Posted on • Updated on • Originally published at focusedlabs.io

Testing Apollos reactive variables in Vuejs and GraphQL

We love Vue.js, we love GraphQL, we love testing, and we love Vue Apollo.

We have been having some great discussions in the office about how to test specific parts of Vue Apollo. They have a great guide on testing that allows you to assert that Mutations were sent, or you can test how a smart query's data causes the Component to render. These are great if your queries are static but what if you have dynamic or reactive variables on your query.

On one hand, you can test the dynamic nature of the query with an e2e test but that feels heavy-handed instead you can test the variables on your query directly.

Say you have this component

const wrapper = mountVue(GroupShow, {
  mocks: {
    $route: {
      params: { userId: this.$route.params.userId },
    },
  },
});

Enter fullscreen mode Exit fullscreen mode

Then a simple test to say the queries variables could be

it('queries the correct group', () => {
  const data = {
    userId: 6,
  };

  const wrapper = mountVue(GroupsIndex, {
    mocks: {
      $route: {
        params: { userId },
      },
    },
  });

  wrapper.setData(data);

  expect(
    wrapper
      .vm
      .$options
      .apollo
      .groups
      .variables
      .bind(wrapper.vm)().userId,
  ).toEqual(6);
});
Enter fullscreen mode Exit fullscreen mode

A couple of things to note.

  1. I only feel obligated to test the variables function because I trust Vue Apollo to handle the variables correctly.
  2. Notice the Function.bind call. When executing the function outside of Vue's event loop you don't have the same this so you need to bind back to the wrapper's view model.

Hopefully, this saves someone some time!

Top comments (1)

Collapse
 
austinbv profile image
Austin Vance • Edited

Any typescript junkies out there, if you can find a better way

const groups = wrapper.vm.$options.apollo!.groups as VueApolloQueryDefinition;
const variables = groups.variables!.bind(wrapper.vm) as () => OperationVariables;
wrapper.setData(data);
expect(variables().zip).toEqual(zip);
expect(variables().zip).toEqual(zip);