Testing Vue Component with Cypress revealed that the function getActivePinia was triggered without an active Pinia instance

Below are the code snippets I'm working with:

Test.vue

<template>
  <button v-show="store.common == 'hi'" @click="func">
    hello world
  </button>
</template>

<script setup>
import {mainStore} from './index.js'
import {check} from './check.js'

function func() {
  check();
}

</script>

check.js

import {mainStore} from './index.js'

// This store needs to be defined in this project.
let store = mainStore();

function check() {
// The store may be updated, for example from backend.
  store.common = 'hello';
}

export {check};

index.js

import {defineStore} from "pinia"

export const mainStore = defineStore('main', {
  state: () => {
    return {
      common: 'hi', 
    }
  },
  getters: {}, 
  actions: {}, 
})

My test file, temp.cy.js

import {mount} from 'cypress/vue'
import { createApp } from 'vue'
import Test from './Test.vue'
import {createPinia, setActivePinia} from "pinia"

describe('for example', () => {
  const app = createApp({});
  beforeEach(() => {
    const pinia = createPinia();
    app.use(pinia);
    setActivePinia(pinia);
  });
  
  it('render', () => {
    mount(Test);
  });
})

When running this test, an error occurs:

getActivePinia was called with no active Pinia. 

I attempted to modify the code in check.js as follows:

import {mainStore} from './index.js'

// This store needs to be defined in this project.
let store = null;

function getStore() {
  if (store === null) {
    store = mainStore();
  }
}

function check() {
  getStore();
  store.common = 'hello';
}

export {check};

or

import {mainStore} from './index.js'
import {onBeforeMount} from 'vue'

// This store needs to be defined in this project.
let store = null;

onBeforeMount(() => {
  store = mainStore();
});

function check() {
  store.common = 'hello';
}

export {check};

Subsequently, the component stops rendering and an error is thrown:

Cannot read properties of undefined (reading common)
How can I resolve this issue? What could be wrong with my code?

Answer №1

The error occurs because there is no connection between the Pinia-powered app you have created and the Test component you are attempting to mount.

To resolve this issue, consider creating a custom mount command following the example provided in the documentation Replicating Plugins

import { createPinia } from 'pinia' // or Vuex
import { mount } from 'cypress/vue'
import { h } from 'vue'

Cypress.Commands.add('mount', (component, ...args) => {
  args.global = args.global || {}
  args.global.plugins = args.global.plugins || []
  args.global.plugins.push(createPinia())

  return mount(() => {
    return h(VApp, {}, component)
  }, ...args)
})

describe('for example', () => {
  it('render', () => {
    mount(Test);
  });
})

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

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

Error encountered with Firebase Modular SDK V9.0.0+: Issue with undefined firebase property 'apps' causing TypeError

Encountered an error while attempting to run my next.js app. Despite trying various methods, I have been unable to resolve it. The version of Firebase I am using is 9.0.1 Server Error TypeError: Cannot read property 'apps' of undefined The error ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...

Stylist in Visual Studio Code for React applications

Whenever I try to save or format my React code using Ctrl + Shift + F, the formatting of the code below seems unusual. Is there a way to fix this issue? The original code is as follows: import logo from './logo.svg'; import './App.css&apos ...

Vue - Unable to navigate to a different route

I just started working with Vue and attempted to redirect '/home' to '/travel', but for some reason it's not functioning correctly. Can someone please guide me on how to achieve this? What could be the issue with my code? Thank y ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Effortlessly update data in real-time using Laravel and vue.js

I am dealing with constantly changing API data in my development work. Utilizing Laravel and Vue.js, I can see a continuous flow of data when monitoring the network using F11. However, this does not seem to have any impact on the DOM. Below are some sampl ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

Bringing in a JavaScript function from a local file into a Node.js

I've been struggling with this issue for a while now and I think it's because of my misunderstanding of how files are linked in node.js. My file structure looks like this: ./main_test.html ./js_test.js ./node_test.js The main_test.html file is ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Instructions for removing a class using the onclick event in JavaScript

Is there a way to make it so that pressing a button will display a specific class, and if another button is pressed, the previous class is removed and a new one is shown? Thank you for your assistance. function myFunction() { document.getElementById ...

Vue unit testing for reactive state functions

Unit testing is a new concept for me, especially when dealing with reactive state in components. I am looking to write unit tests for a component that contains reactive state. Below is an example of the test component: <script setup lang="ts" ...

Incorporate SCSS variables directly into Vue single component files for easy reuse

My goal is to package a repository in npm that holds a directory of Vue single file components, which can be easily imported like so: import { Button } from "@user/design-system" The issue at hand is that the Button.vue file contains variables sourced fr ...

Best practices for utilizing the getTile() method within Google Maps

I have a question about storing markers in a database using tile IDs. The goal is to display all the markers associated with a specific tile when it is displayed on a map. Initially, I created a code that was not working correctly. It only requested one ...

How can I prevent an endless loop in jQuery?

Look at the code snippet below: function myFunction(z){ if(z == 1){ $(".cloud").each(function(index, element) { if(!$(this).attr('id')){ $(this).css("left", -20+'%'); $(this).next('a').css ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Issues with jQuery requests not working properly on the mobile application

Creating a mobile application for Android devices using Intel XDK has been a rewarding experience so far. I have been testing my PHP code on an emulator and local development server (127.0.0.1) through AJAX methods such as $.ajax(), $.post(), and $.get(). ...

Are ES6 arrow functions not supported in IE?

When testing this code in my AngularJs application, it runs smoothly on Firefox. However, when using IE11, a syntax error is thrown due to the arrows: myApp.run((EventTitle, moment) => { EventTitle.weekView = event => \`\${moment(event.s ...

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...