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

The XMLHttpRequest onload() function is failing to pass an instance of the XMLHttpRequest object

I am facing an issue with a function that sends a basic AJAX request to my server. The JavaScript code in the browser is as follows: function testRequest() { var xhr = new XMLHttpRequest(); xhr.onload = () => { console.log("RESPONSE R ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

Steps for incorporating a toggle feature for displaying all or hiding all products on the list

Looking for some guidance: I have a task where I need to display a limited number of products from an array on the page initially. The remaining items should only be visible when the user clicks the "Show All" button. Upon clicking, all items should be rev ...

Please disregard this issue: The client-rendered virtual DOM structure does not align with the server-side rendered content

What is the best way to achieve full force rehydration? I often encounter this issue with if clauses, using variables for lazy requests on the client side. When this error occurs, it completely halts the client-side app from running (Hydrating) in a Produc ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

What could be causing the issue with my css `content:` not functioning across different browsers, and how can I enhance cross-browser compatibility in all cases

Working on my first HTML/CSS project, I encountered a browser compatibility challenge. The code functions well in Firefox, IE, and Edge but fails in Chrome. Specifically, I am trying to make a button display alternating up and down arrows when clicked. Whi ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

How can I programmatically close the Date/Time Picker in Material UI Library?

Is there a way to programmatically close the Date/Time Picker in Material UI Library? ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Issues surrounding the determination of CSS attribute value using .css() function within a variable

I have been working on a function to change the color of a span dynamically from black to a randomly selected color from a predefined list. However, I am encountering an issue with the .css("color", variableName) part of my code and suspect that my synta ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Adding a URL link to a mentioned user from angular2-mentions within an Angular 4 application can be achieved in the following way:

Need help with adding a URL RouterLink to mention a user using angular2-mentions. This is the code snippet I currently have: <div class="col-sm-12"> <input type="text" [mention]="contactNames" [mentionConfig]="{triggerChar:'@',maxI ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

Utilizing HTML5 data attributes to store intricate JSON objects and manipulate them using JavaScript

Recently, I encountered a unique challenge that I set for myself... I am currently in the process of developing an advanced ajax content loader plugin that comes with an array of options and callbacks. In order to streamline the initialization process and ...

When utilizing the withStyles HOC, innerRef is not included in the passing of other props when passed through React.forwardRef

I have encountered a problem while passing the ref using React.forwardRef to the down component. This method usually works fine. <SomeComponent component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)} .../> Ho ...

AngularJS: Monitoring $locationChangeStart for token verification

I am attempting to check if the next has a token or not, but it is not working and I am getting an error: TypeError: Cannot read property 'next' of undefined Any suggestions? app.js .run(function ($rootScope, $location,$log,User) { ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...