简体   繁体   中英

Snapshot test using vue is failing with "TypeError: Cannot read property of undefined"

The component itself works on the page with no errors.

So does storybook, the only issue is the unit test.

import { mount } from '../../vue';
import { createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import SessionGymChart from '@/components/SessionGymChart.vue';

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

const defaultprops = {
  endDateOveride: '',
  totalHours: 0,
  sessionsTotal: 1,
  isLoading: false,
  hasTooMuchData: false,
  swapChart: false,
  chartData: {}
};

describe('SessionGymChart', () => {
  let store;
  beforeEach(() => {
    store = new Vuex.Store({
      state: {
        user: { billing: true },
        chartData: {
          days: 10,
          sessions: [
            {
              id: '324365egdfgfd',
              sessionReference: '056343',
              dateStarted: '2022-08-26T16:23:14.909Z',
              dateEnded: '2022-08-26T16:23:22.000Z',
              userId: 'dfgdfgdfg545645',
              userDisplayName: 'Tester'
            }
          ]
        }
      },
      mutations: {},
      actions: {}
    });
  });

Is there anything obvious I'm doing wrong? There is a computed property where it breaks on the component. It seems like it can't access the sessions data (saying undefined) and I'm not sure why as it is inside defaultprops.

This is where it shows to be breaking in the component, at a computed property and this shows on the snapshot error.

gymSeries() {
      const { sessions } = this.chartData ? this.chartData : {};
    > if (sessions.length === 0) return {};
                                           ^
      else {
         const sessionsUsage = sessions.map(x => {
         return {

Any help would be much appreciated!

This actually returns undefined if this.chartData is undefined :

const { sessions } = this.chartData ? this.chartData : {};

The problem there is that you're destructuring chartData , and you expect the return value of the ternary statement to be an object that contains a sessions property.
If chartData is undefined , that results in:

const { sessions } = {};

You can fix that by adding an empty sessions property:

const { sessions } = this.chartData ? this.chartData : { sessions: {} };

Or, shorter, using optional chaining:

const sessions = this.chartData?.sessions || {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM