The return value from the (VUEX + JEST) function is not defined

While working on a test, I ran into an issue. Despite double-checking everything, I can't seem to call the function correctly. Can anyone please assist me with this?

The code in index.vue looks like this:

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import Login from '../index'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Testing the login page', () => {

    let actions
    let store
    let loginData = {username: 'user1', password: '123'}

    beforeEach (() => {
        actions = {
            handleLogin: jest.fn(),
            login: jest.fn()
        }
        store = new Vuex.Store({
            actions
        })
    })

    it('Sending the login action', () => {
        const wrapper = shallowMount(Login, {
            computed: {
                loginBtn: () => true,
                loginStatus: () => '',
                showLogoutEverywhereBtn: () => false
            },
            store,
            localVue
        })

        wrapper.find('.main-form__login-submit').trigger('click')
        expect(actions.handleLogin).toHaveBeenCalled()
    })
});

This is how the function in index.vue looks:

...
methods: {
        handleLogin(e) {
            e.preventDefault()
            this.$store.dispatch('login', this.loginForm)
                .then((response) => {
                    console.log('login page response: ', response)
                    if (response.id_user !== undefined) {
                        this.$router.push({ path: '/' })
                    }
                })
                .catch((e) => {
                    console.log('Error inside: ', e);
                });
        },
...

Looking at my user.js file:

...
actions: {
        // handling user login
        login({ commit }, userInfo) {
            console.log('Information in store/modules/user.js: ', userInfo)
            const { username, password } = userInfo
            return new Promise((resolve, reject) => {
                login({ user_login: username.trim(), user_password: password }).then(response => {            
                    const decoded = jwtDecode(response)
                    console.log(decoded)
                    /***********************SOCKET.IO***************************/
                    let data = { userId: decoded.id_user, page: 'login' }
                    socketUrl.emit('authorize', data, (flag) => {
                        console.log('Main authorize here.')
                        console.log('This is store token id:', decoded.id_user)
                        console.log(flag)
                        if (decoded.status === 0) {
                            commit('CHANGE_SELECTED_USER_STATUS_ID', 392)
                            console.log(decoded.full_name)
                            // commit('SET_TOKEN', decoded)
                            commit('AUTH_SUCCESS', decoded)
                            if (flag) {
                                resolve(decoded)
                                console.log('This is decoded: ', decoded.statuses[0])
                                getStatusesArray().then(response => {
                                    console.log('This is presencestatus data:', response)

                                    commit('UPDATE_STATUS', response)
                                })
                            } else {
                                commit('AUTH_ERROR')
                            }
                            resolve() 
                        } else {
                            commit('AUTH_ERROR')
                        }
                    })
                    socketUrl.on('kick', (message) => {
                        console.log('socket: ', message)
                        commit('DUPLICATE_LOGIN', message.text)
                    })
                    socketUrl.on('message', () => {
                        commit('AUTH_ERROR')
                    })
                    /***********************SOCKET.IO***************************/
                }).catch(error => {
                    console.log('Error in store/modules/user.js login: ', error)
                    commit('AUTH_ERROR')
                    reject(error)
                })
            })
        },

        logout(state, payload) {
            state = null
            console.log('User logged out with userId: ', payload)
            socketUrl.emit('disconnectUser', { userId: payload }) 

            return new Promise ((resolve, reject) => {
                logout({ userId: payload })
                    .then(response => {
                        console.log('logout function', response)
                        resolve(response)
                    })
                    .catch((e) => {
                        console.log('logout error: ', e)
                        reject(e)
                    })
            }) 
        },
...

Any help would be greatly appreciated. This testing challenge has been consuming a lot of my time, especially since I'm still new to it. It's possible that I'm missing something related to passing parameters to the function. Thank you in advance!

Answer №1

Aha, the truth is revealed:

Ahoy! You're imitatinghandleLogin as a store action. However, it's actually not a store action, but indeed your method housed in a component.

Here's the solution for you:

... // your previous snippet

wrapper.setMethods({ handleLogin: jest.fn() })  // insert this line here
wrapper.find('.main-form__login-submit').trigger('click')

... // continue with your subsequent code

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

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

Logging in requires attention to detail when using PGSQL and SQLite as the usernames and

Currently, I am utilizing Laravel 9x along with Jetstream and Inertia/Vue. I've observed that when using PGSQL and SQLite, the login for email is case sensitive. How can this issue be resolved? Although I haven't included any code in this post as ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...

Is it possible to remove the v-main element?

Can anyone help me figure out what the big purple square at the bottom of my page is and how to delete it? https://i.stack.imgur.com/bMVOu.jpg <template> <v-app> <template> <header> <div> <Header ...

When the window size is reduced, the navigation vanishes

Whenever I resize the window, the navigation bar disappears. Here is the image of the page before resizing the window https://i.sstatic.net/UiRB9.png Below is the image after resizing the window https://i.sstatic.net/X00d2.png Displayed below is the cod ...

Customize the text that appears when there are no options available in an Autocomplete component using React

Recently, I came across this Autocomplete example from MaterialUI that caught my attention. https://codesandbox.io/s/81qc1 One thing that got me thinking was how to show a "No options found" message when there are no search results. ...

Utilizing Javascript in Spotfire for enhanced functionality

Currently, I have a dropdown menu with two options ("START" & "END"). Depending on the selected value from this dropdown, I want to display a specific DIV element. I attempted to use the code below, but unfortunately, it is not functioning as expected ...

picker and calculator for selecting date ranges

I'm currently working on a hotel booking form where prices are calculated based on the number of adults, seniors, and students. I'm trying to add a date range picker feature that will determine the total cost depending on the selected number of d ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

Deconstructing arrays in the req.body object in a Node.js Express application

Received an array in the request body as follows: [ { "month" : "JUL", "year" :"2018" }, { "month" : "JAN", "year" :"2018" }, { "month" : "MAR", "year" :"2018" } ] This array consists of two parameters (month:enum and year:string). ...

Ways to improve the cleanliness of the code

I've created a simple life simulation game and I'm looking for ways to optimize the code. Any suggestions on how to make the code cleaner? jsfiddle: https://jsfiddle.net/04vazdrb/ /* JavaScript Implementation of Conway's Game Of Li ...

Combining the inline JavaScript linting tool ESLint with the popular Airbnb configuration and Facebook

In my current project, I am utilizing ESLint and looking to incorporate Facebook flow. However, I am encountering warnings from ESLint regarding flow type annotations. Within the project root directory, I have both .flowconfig and .eslintrc files present. ...

Troubleshooting WebView JavaScript Functionality in Android Development

protected void onCreate(Bundle savedInstanceState) { String javaScript = "javascript:(function(){var%20content=document.getElementsByClassName('entry-content')[0].innerHTML;var%20content2=content.replace(/<p>/,'');var%20endpos ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

Retrieving the passed argument variable and utilizing it as a key in a map

I've been working on a JavaScript project recently and I've encountered a situation where I believe my code could be significantly reduced - up to 50% - if I could access the passed arguments to a function and use them as keys. Since I'm sti ...

The jQuery document.ready event fails to trigger when invoked after using ScriptManager.RegisterStartupScript in the code-behind

I am currently working with a filtered list of items utilizing a tool called Check out the screen for a visual example. In the user flow, after selecting to add another action, a fancybox popup is triggered displaying the next image: After the user adds ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Should You Ajaxify Your Website?

Absolutely loving the way Ajax can transform a web app into something that performs like a desktop application. The concern, however, arises when dealing with high volume sites. Currently working on an intranet-based database app meant for only 2-4 users a ...

Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently w ...