Vue snapshot testing is encountering a failure with the error message "TypeError: Cannot read property of undefined"

Everything seems to be working fine with the component on the page without any errors.

Storybook is also functioning well, but the problem lies in 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: {}
    });
  });

Could there be something obvious that I'm missing? There's a computed property where it fails within the component. It appears to have trouble accessing the sessions data (showing undefined) even though it's part of defaultprops.

This is the point of failure in the component at a computed property, leading to a snapshot error.

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

Any assistance would be highly appreciated!

Answer №1

If this.chartData is undefined, the code snippet will return undefined. Here's the original code:

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

The issue lies in assuming that the ternary statement will always return an object with a sessions property within it when chartData is not undefined.

const { sessions } = {};

To resolve this, you can add an empty sessions property like this:

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

Alternatively, you can make it shorter using optional chaining:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Deploying Your NuxtJS Project on a Shared Hosting Service

After creating my NuxtJS project locally, I am now facing the challenge of deploying it to a shared hosting provider like Host Gator. Since I intend to utilize the server side rendering feature of NuxtJS, I know I need to execute the following command: n ...

Issue encountered while retrieving information from XML file through AJAX

I am facing an issue while using AJAX to fetch data from an external XML file. The error I receive is "Invalid argument" and I am working with IE 8. Below is the code snippet: var xhr; xhr = new XMLHttpRequest(); xhr.open("GET","C:/Users/abc/Desktop/Pr ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

Obtaining rotate3d values using JavaScript / jQuery

When dealing with an element that has a transformation like the following: style="transform: rotate3d(1, 0, 0, -50deg);" I am looking to extract the value -50 using Javascript or jQuery. It's essential for me to get the absolute value, so negative d ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

Setting up electron with vuejs and tailwindcss: a step-by-step guide

Setting up a project from the ground up using these particular technologies has proven to be a challenge for me. I'm curious if it's possible to integrate nuxtjs with electronjs. electronjs vuejs tailwindcss ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Jquery Plugin fails to generate dynamic elements effectively

I developed a masking jQuery script that dynamically adds elements to an existing input element. var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>'); wrapper: function() { container = $(container) ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

JavaScript Method for Retrieving Form Element Values

I am currently working on retrieving the value of an input element in a popup window that is launched from a parent page. Here is my code, but I am facing difficulties in obtaining the pc value from the input field. <html> <head> <? $pid= ...

Avoiding HTML in JavaScript: Tips and Tricks

My application generates numerous elements dynamically based on server data in JSON format. This process involves embedding a significant amount of HTML directly within my JavaScript code, leading to pollution and making it increasingly challenging and l ...

The animation functionality for Ionic Vue Router on iOS seems to be malfunctioning

I have recently set up a new Ionic Vue app using the tabs template and encountered an issue after switching the mode to ios - the routing animations disappeared. The animations work fine with md. This is what my index.html looks like: <!DOCTYPE html> ...

best practices for data flow between components in React using hooks

I have successfully retrieved data from my database in the Recipes component. Now, I am attempting to pass this data into the RecipeList component. However, when I do so, only the bullet points are showing up in the RecipeList component and for some reas ...

AngularJS Login Popup with SpringSecurity

I have successfully integrated spring security with my AngularJS webpage utilizing Rest API. However, I am facing an issue where every time I attempt to log in using the rest api from my customized login page, it prompts me for the login credentials in a p ...

Synchronizing Form Data in Angular 5: Pass and Populate Dropdowns between Components

I have developed a unique form (material dialog modal) that allows users to create an account. When the user clicks on the Register button, their created account should appear in a dropdown menu without redirecting or reloading the current page. I am facin ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...