Search code examples
javascriptvue.jsjestjsvuexvue-test-utils

How to test Vuex correctly?


I need your help with testing Vuex store (never done this before and unfortunately hard to understand ).

I have two buttons, and I need to test that they call two different functions that return something.

Buttons:

...
<input class="main-form__login-submit" v-if="this.loginBtn" type="submit" @click="handleLogin" value="Войти" />

<input class="main-form__login-submit main-form__login-session" v-if="this.showLogoutEverywhereBtn" type="button" @click="websocketAuth" value="Выйти из других окон" />
...

Methods:

...
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);
                });
        },
        websocketAuth(e) {
            e.preventDefault()
            console.log('login:  ', this.loginForm.username, this.loginForm.password)
            this.$store.dispatch("logoutEverywhere", {
                user_login: this.loginForm.username,
                user_password: this.loginForm.password
            })
                .then((resp) => {
                    let data = { userId: resp, page: 'login' }
                    socketUrl.emit('logoutEverywhere', data, (flag) => {
                    if(flag) {
                        this.$store.dispatch('duplicateLoginClear')
                    }
                    console.log(flag)
                    })

                    console.log('1 ', resp)
                })
        }
    }
...

Thank you in advance!


Solution

  • You need to use jest mocks ( if using jest ).

    Heres a quick tutorial on it.

    https://codeburst.io/a-pattern-for-mocking-and-unit-testing-vuex-actions-8f6672bdb255