Search code examples
javascriptvue.jsjestjsvue-test-utils

(VUEX + JEST) Function response is undefined


I encountered a problem while writing a test. I can’t call the function, although everything seems to be written correctly. Please help!

index.vue:

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

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Проверяем страницу входа в систему', () => {

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

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

    it('Отправляем экшн логирования', () => {
        const wrapper = shallowMount(Login, {
            computed: {
                loginBtn: () => true,
                loginStatus: () => '',
                showLogoutEverywhereBtn: () => false
            },
            store,
            localVue
        })

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

Here is my function in index.vue:

...
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('ты внутри ошибки: ', e);
                });
        },
...

Here is my user.js:

...
actions: {
        // user login
        login({ commit }, userInfo) {
            console.log('store/modules/user.js userInfo: ', 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() // TODO: зачем это здесь?
                        } else {
                            commit('AUTH_ERROR')
                        }
                    })
                    socketUrl.on('kick', (message) => {
                        console.log('store.js socket: ', message)
                        commit('DUPLICATE_LOGIN', message.text)
                    })
                    socketUrl.on('message', () => {
                        commit('AUTH_ERROR')
                    })
                    /***********************SOCKET.IO***************************/
                }).catch(error => {
                    console.log('store/modules/user.js login error: ', error)
                    commit('AUTH_ERROR')
                    reject(error)
                })
            })
        },

        logout(state, payload) {
            state = null
            console.log('Logout 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)
                    })
            }) 
        },
...

I will be very grateful to anyone who will help. Since I'm new to testing, this problem is taking me a lot of time. Maybe somewhere I need to pass the parameters to the function (I'm not sure where exactly). Thank you in advance!


Solution

  • Now I see it:

    Look, you are mockinhandleLogin as a store action. But it is NOT your store action. It is your method in a component.

    So what you need to do is:

    ... // your previous code
    
    wrapper.setMethods({ handleLogin: jest.fn() })  // add this line here
    wrapper.find('.main-form__login-submit').trigger('click')
    
    ... // your next code