Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would return false. Is it not possible to mock Actions without replicating their actual functionality using jest.fn()? I'm confused as to why I am unable to achieve this.

store.js

export default new Vuex.Store({
  state: {
    currentSequence: ''
  },
  actions: {
    runGenerator({ commit, state }, currentSequence) {
      // do something with currentSequence
    }
  }
})

Home.vue (Note that this is not the complete code for this component, but includes important sections such as the submit.prevent method, the form html, and where the vuex action is called)

<template>
  <v-app id="inspire">
    <v-form @submit.prevent="setNextVal" id="sequence-form">
      <!-- form contents here -->
    </v-form>
  </v-app>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    setNextVal() {
      this.runGenerator(this.form.currentSequence)
      this.form.currentValue = this.getCurrentValue
    },
    ...mapActions([
      'runGenerator'
    ]),
  }
}
</script>

store.spec.js

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vue from 'vue'
import Vuex from 'vuex'
import Vuetify from 'vuetify'
import Home from '@/views/Home.vue'

const localVue = createLocalVue()

localVue.use(Vuex)
Vue.use(Vuetify)

describe('Home.vue', () => {

  let actions
  let store

  beforeEach(() => {
    actions = {
      runGenerator: jest.fn()
    }
    store = new Vuex.Store({
      state: {
        currentSequence: ''
      },
      actions
    })
  })

  it('Dispatches "runGenerator" when submit.prevent has been triggered', () => {
    const wrapper = shallowMount(Home, { store, localVue })
    const form = wrapper.find('#sequence-form')
    form.trigger('submit.prevent')

    expect(actions.runGenerator).toHaveBeenCalled()
  })
})

Upon running the test, I received the following error:

expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called

What could be the missing piece? I would appreciate any insights or alternative solutions you might have. I have extensively reviewed online references, but haven't found any other solutions thus far.

Answer №1

While you may be making fun of the actions, they are still considered asynchronous in nature. When testing vuex, I always make sure to await async actions using flushPromises (which guarantees that any ongoing promises are resolved before moving forward with execution). To incorporate flushPromises into your project, follow these steps:

npm i -D flush-promises

After that, in your test script:

import flushPromises from 'flush-promises'

//...

it('Triggers "runGenerator" when submit.prevent is activated', async() => {
    const wrapper = shallowMount(Home, { store, localVue })
    const form = wrapper.find('#sequence-form')
    form.trigger('submit.prevent')

    await flushPromises();    

    expect(actions.runGenerator).toHaveBeenCalled()
})

Keep in mind that the test function has now been marked as async.

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

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

What is the best way to implement a path alias in Vue component imports when using Vite?

When utilizing Vue single file components in Vite, I have found that using a baseUrl and path alias in my tsconfig.json file allows me to import *.ts files into component files without any issues. However, when attempting to import *.vue files using the sa ...

What could be preventing this Javascript from executing?

Can anyone help me troubleshoot why the JavaScript code is not executing in this HTML file? The console isn't showing any errors. Any suggestions? <!doctype HTML> <html> <head> <title>ProjectShare</title> ...

Obtain the value of the background image's URL

Is there a way to extract the value of the background-image URL that is set directly in the element tag using inline styling? <a style="background-image: url(https:// ....)"></a> I attempted to retrieve this information using var url = $(thi ...

What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong? let posts = [ {name: '1', data: 'Hi1'}, ...

What is the correct method for completely eliminating a mesh from the three.js scene?

I am looking for a way to fully remove meshes from a three.js scene without causing any memory leaks. I have noticed that reloading the same models multiple times can lead to browser crashes, indicating that memory is not being properly deallocated. ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Tips for inserting items into an array of objects?

I have an array of objects with categories and corresponding points, and I need to calculate the total points for each category. { category: A, points:2 }, { category: A points: 3 }, { category: B, points: ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...

Revise a function that locates an object with a corresponding id in an array, modifies a property, and updates a React component's state

Here is a function that takes in a rating value within an object. The ID and Question properties remain unchanged, but the rating value can be updated. This will result in updating a React state value. Is there a method to improve the readability and con ...

Utilizing NodeJS application to connect to Sharepoint 2019 On-Premises Web Services

Recently, I/T in my organization set up a new Sharepoint 2019 OnPromise with a hybrid configuration that utilizes Azure AD for authentication. As the site collection admin for our Sharepoint website, the URL to access it is Upon accessing this URL, I am ...

What is the best way to retrieve all dates that are older than 30 days using JavaScript?

I have the following code snippet as a reference and I'm attempting to retrieve a list of dates from 30 days before. What do I need to change? Date.prototype.addDays = function(days) { var newDate = new Date(this.valueOf()) newDate.s ...

Tips for customizing the event target appearance in Angular 2?

After following the steps outlined in this particular blog post (section 3, event binding), I successfully added an event listener to my component class. I can confirm that it responds when the mouse enters and exits. <p class="title" (mouseenter)="unf ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Using JavaScript to add a JSON string from a POST request to an already existing JSON file

I am currently working on a basic express application that receives a post request containing JSON data. My goal is to take this data and add it to an existing JSON file, if one already exists. The key value pairs in the incoming JSON may differ from those ...