0

I have a component that I want to test that uses Vuex.

components/Main/Header.vue

<template>
  <v-container fluid grid-list-xl>
    <v-card flat class="header" color="transparent">
      <v-layout align-center justify-start row fill-height class="content">
        <v-flex xs5>
          <v-img :src="avatar" class="avatar" aspect-ratio="1" contain></v-img>
        </v-flex>
        <v-flex xs7>
          <div class="main-text font-weight-black">
            WELCOME
          </div>
          <div class="sub-text">
            {{currentLocation.description}}
          </div>
          <div @click="showStory" class="show-more font-weight-bold"> 
            Explore More
          </div>
        </v-flex>
      </v-layout>
    </v-card>
  </v-container>
</template>

<script>
  import avatar from '../../assets/images/home/avatar.png';

  export default {
    name: 'Header',
    computed: {
      currentLocation() {
        return this.$store.getters.getCurrentLocation;
      },
      avatar() {
        return avatar;
      }
    },
    methods: {
      showStory() {
        this.$router.push( { name: 'Stories',  params: { name: 'Our Story' } });
      }
    }
  }
</script>

and from /test/unit/components/Main/Header.spec.js

import Vuex from 'vuex'
import { shallowMount, createLocalVue } from "@vue/test-utils"
import Header from "@/components/Main/Header.vue"

const localVue = createLocalVue()
localVue.use(Vuex)

const store = new Vuex.Store({
  state: {
    currentLocation: {
      name: 'this is a name',
      description: "lorem ipsum",
      latitude: '1.123123',
      longitude: '103.123123',
      radius: '5000'
    }
  },
  getters: {
    getCurrentLocation: (state) => state.currentLocation
  }
})

describe('Header', () => {

  const wrapper = shallowMount(Header, {
    store,
    localVue
  })

  it('should render a computed property currentLocation', () => {
    expect(Header.computed.currentLocation()).toBe(store.getters.getCurrentLocation)
  });

});

The error I'm getting is from the computed property currentLocation TypeError: Cannot read property 'getters' of undefined

AllenC
  • 2,754
  • 1
  • 41
  • 74
  • 2
    I think you should be checking `wrapper.vm.currentLocation` not `Header.computed.currentLocation()` – Adam Orłowski Mar 07 '20 at 13:50
  • [Yilmaz](https://stackoverflow.com/users/14182305) posted an [Answer](https://stackoverflow.com/a/66510835) saying "is this nuxt project? Maybe [this](https://medium.com/@brandonaaskov/how-to-test-nuxt-stores-with-jest-9a5d55d54b28) helps." – Scratte Mar 07 '21 at 10:53

0 Answers0