DEV Community

Discussion on: Testing vue-apollo Components with Jest

Collapse
 
austinbv profile image
Austin Vance

You have a great series of blog posts.

One thing we have struggled to test is dynamic queries or variables in smart queries.

Vue.extend({
  name: 'TestComponent',
  apollo: {
    human: {
      query: gql`query GetHumans($ID: ID!) {
      human(id: $id) {
        name
        height
      }
    }`,
    },
    variables() {
      return {
        id: this.$route.params.id,
      };
    },
  },
});

I would love to write a test that is something like


it('gets queries for the correct user', () => {
  mount(TestComponent, {
    mocks: {
      params: {
        id: "1"
      }
    }
  })

  // expect query to be called with an ID of "1"
})

It seems like because vue-apollo isn't mounted in test we cant test the variables function directly or indirectly as it doesn't exist on the vm. Is there a way to get at the apollo section of the vm in test?

Cheers!

Collapse
 
n_tepluhina profile image
Natalia Tepluhina

You can try to play with mocking $apollo object on mounting. I've added this section to Vue Apollo docs recently: vue-apollo.netlify.com/guide/testi...

Please let me know if it's useful for your case! If it's not, we'll try to figure out the best way to do it

Collapse
 
austinbv profile image
Austin Vance • Edited

I decided to test the variables functions directly.

the winning incantation is

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

// @ts-ignore
expect(wrapper
  .vm
  .$options
  .apollo
  .groups
  .variables
  .bind(wrapper.vm)().zip
).toEqual(50500);

// @ts-ignore
expect(
  wrapper.
  vm.
  $options.
  apollo.
  groups.
  variables.
  bind(wrapper.vm)().userId
).toEqual(6);

I'm working a mock provider that provides access to stuff thing this so it's a bit less of a dig to test

Thanks!

Thread Thread
 
austinbv profile image
Austin Vance

I posted a short blog post for people about this

dev.to/focusedlabs/testing-apollos...