Attempting to test Vuex getters that return undefined when provided with an argument results in an error indicating

Currently, I have set up karma and chai for testing purposes and I am attempting to follow the Testing Getters example available here

Below is the code snippet from my fruits.js store:

// fruits.js store
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const fruits = new Vuex.Store({
  state: {
    fruits: [
      {id: 1, name: 'Apple'},
      {id: 2, name: 'Banana'},
      {id: 3, name: 'Orange'}
    ]
  },
  mutations: {
  },
  actions: {
  },
  getters: {
    getFruitById (state, {id}) {
      return state.fruits.find(fruit => {
        return fruit.id === id
      })
    }
  }
})

Additionally, here is a glimpse of my fruit.spec.js file:

// fruit.spec.js
import { expect } from 'chai'
import { fruits } from '../../../../src/store/fruits'

describe('getters', () => {
  it('getFruitById()', () => {
    // mock data
    const state = {
      fruits: [
        {id: 1, name: 'Apricot'},
        {id: 2, name: 'Kiwi'},
        {id: 3, name: 'Watermelon'}
      ]
    }
    const id = 1
    // find fruit by id
    const result = fruits.getters.getFruitById(state, {id})
    expect(result).to.deep.equal([
      {
        id: 1,
        name: 'Apricot'
      }
    ])
  })
})

Upon running the test in my fruit.spec.js, an error message "undefined is not a function" appears on line

const result = fruits.getters.getFruitById(state, {id})

The main issue lies in the fact that the mock state in fruit.spec.js is not being passed correctly into fruit.js

What steps can be taken to ensure the successful execution of the test?

Answer №1

To effectively test your getters individually, it is recommended to export them separately:

// fruits.js store
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const getters = {
  getFruitById (state, {id}) {
    return state.fruits.find(fruit => {
      return fruit.id === id
    })
  }
}

export const fruits = new Vuex.Store({
  state: {
    fruits: [
      {id: 1, name: 'Apple'},
      {id: 2, name: 'Banana'},
      {id: 3, name: 'Orange'}
    ]
  },
  mutations: {
  },
  actions: {
  },
  getters,
})

You can then access these individual getters in the unit tests as shown below:

import { getters } from '../../../../src/store/fruits'
// ...
    const result = getters.getFruitById(state, {id})
// ....

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

Change button text with JS on click

My goal is to update the text on a button click, changing it from 'Copy' to 'Copied!' as part of a custom clipboard implementation. The code I'm currently using is as follows: HTML: <button id="copyButton2">Copy</button& ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

Is it possible to use Docxtemplater.js in a browser without familiarity with Node, Browserify, or npm?

I'm trying to get Docxtemplater.js to function properly on a browser. Unfortunately, I lack knowledge in areas such as Node.js, Browserify.js, "npm", "bower", and other technical aspects commonly found in modern JavaScript libraries. While I do inten ...

In general, I am seeking ways to streamline my code that is excessively repetitive. More specifically, I am attempting to utilize a single function to access multiple states

Looking for assistance with my new project related to enhancing my skills in react/javascript. I am creating a dice rolling application specifically for tabletop gaming. The aim is to allow users to roll any number of dice of the same size, as well as mult ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...

Is JavaScript ES6 reassigning or just a parameter?

Could someone provide an explanation for what's going on here? I am familiar with express middleware, but I'm interested in understanding the syntax. I grasp the ES6 syntax for mustBeLoggedIn, but I'm unsure about the purpose of const forbi ...

Looking to send an HTTP request to submit a form within a Node.js application to an external website?

Can someone help me with submitting a form on a different site and receiving a response? I'm having trouble figuring out how to do this. Here is the website I am targeting: Below is my code snippet: var http = require('http'); var options ...

Is there a way to automatically mount tabs without manually clicking on them?

Looking to optimize data fetches within a large tab container in React using material-ui. My goal is to have each Tab component handle its own data fetching, especially for Tabs with a greedyLoad prop that will be mounted upon the initial mounting of the T ...

Combining href into click events - a step-by-step guide

I have an href link available. '<a href="index.php?imei=' + value['imei'] + '&nama=' + value['nama'] + '" class="summarykapal">Summary</a>' This is the function in question: function retr ...

When first accessing the page, the map may not load properly. However, a simple refresh of the page in VueJS should resolve this issue and allow the

After initially loading the page, the map may not work properly in Vue.js. However, refreshing the page fixes this issue. Can anyone provide assistance with this problem? Here is the relevant code: mounted() { this.geolocate(); }, methods: { ...

Editing input within a Bootstrap 4 popover causes it to lose focus

I am using Bootstrap 4 along with the Bootstrap colorpicker to implement a colorpicker within a popup that includes an input field for setting the color code. However, I am facing an issue where the input field (#color-value) seems uneditable when the popo ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

Developing a JSONP functionality

I am currently trying to use JSONP in order to display data within my div. However, the code is not showing anything. I have also included jquery.jsonp.js in my project with the following path: PRJFOLDER->WEBPages->JavaScript->qu ...

Storing data retrieved from an asynchronous call in AngularJS to a variable

Here is the code where I am attempting to utilize promise to store data from an asynchronous call in a variable, but it's not functioning as expected. I am relatively new to promises and after some research, I learned that promises can be helpful in s ...

Updating the material-ui checkbox state to reflect the checked, unchecked, or indeterminate status, can be achieved in reactjs without relying on state

I am currently using Material-UI checkbox components and I have a requirement to programmatically change the state of checkboxes to be checked, unchecked, or indeterminate based on the click of another checkbox. This action needs to be applied to a list of ...