failed to configure axios with django rest auth to login and get auth token - vue.js

I tried these codes:
src/api/auth.js
import session from "./session";
export default {
login(Username, Password) {
return session.post("/auth/login/", { Username, Password });
},
logout() {
return session.post("/auth/logout/", {});
},
createAccount(username, password1, password2, email) {
return session.post("/registration/", {
username,
password1,
password2,
email
});
},
changeAccountPassword(password1, password2) {
return session.post("/auth/password/change/", { password1, password2 });
},
sendAccountPasswordResetEmail(email) {
return session.post("/auth/password/reset/", { email });
},
resetAccountPassword(uid, token, new_password1, new_password2) {
// eslint-disable-line camelcase
return session.post("/auth/password/reset/confirm/", {
uid,
token,
new_password1,
new_password2
});
},
getAccountDetails() {
return session.get("/auth/user/");
},
updateAccountDetails(data) {
return session.patch("/auth/user/", data);
},
verifyAccountEmail(key) {
return session.post("/registration/verify-email/", { key });
}
};
src/session.js
import axios from "axios";
const CSRF_COOKIE_NAME = "csrftoken";
const CSRF_HEADER_NAME = "X-CSRFToken";
const session = axios.create({
xsrfCookieName: CSRF_COOKIE_NAME,
xsrfHeaderName: CSRF_HEADER_NAME
});
export default session;
src/store/auth.js
import auth from "../api/auth";
import session from "../api/session";
import {
LOGIN_BEGIN,
LOGIN_FAILURE,
LOGIN_SUCCESS,
LOGOUT,
REMOVE_TOKEN,
SET_TOKEN
} from "./types";
const TOKEN_STORAGE_KEY = "TOKEN_STORAGE_KEY";
const initialState = {
authenticating: false,
error: false,
token: null
};
const getters = {
isAuthenticated: state => !!state.token
};
const actions = {
login({ commit }, { username, password }) {
commit(LOGIN_BEGIN);
return auth
.login(username, password)
.then(({ data }) => commit(SET_TOKEN, data.key))
.then(() => commit(LOGIN_SUCCESS))
.catch(() => commit(LOGIN_FAILURE));
},
logout({ commit }) {
return auth
.logout()
.then(() => commit(LOGOUT))
.finally(() => commit(REMOVE_TOKEN));
},
initialize({ commit }) {
const token = localStorage.getItem(TOKEN_STORAGE_KEY);
if (token) {
commit(SET_TOKEN, token);
} else {
commit(REMOVE_TOKEN);
}
}
};
const mutations = {
[LOGIN_BEGIN](state) {
state.authenticating = true;
state.error = false;
},
[LOGIN_FAILURE](state) {
state.authenticating = false;
state.error = true;
},
[LOGIN_SUCCESS](state) {
state.authenticating = false;
state.error = false;
},
[LOGOUT](state) {
state.authenticating = false;
state.error = false;
},
[SET_TOKEN](state, token) {
localStorage.setItem(TOKEN_STORAGE_KEY, token);
session.defaults.headers.Authorization = `Token ${token}`;
state.token = token;
},
[REMOVE_TOKEN](state) {
localStorage.removeItem(TOKEN_STORAGE_KEY);
delete session.defaults.headers.Authorization;
state.token = null;
}
};
export default {
namespaced: true,
state: initialState,
getters,
actions,
mutations
};
src/views/Login.vue
<template>
<div>
<form class="login" #submit.prevent="login">
<h1>Sign in</h1>
<label>Username</label>
<input required v-model="Username" type="text" placeholder="Name" />
<label>Password</label>
<input
required
v-model="Password"
type="password"
placeholder="Password"
/>
<hr />
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
Username: "",
Password: ""
};
},
methods: {
/*login() {
let Username = this.Username;
let Password = this.Password;
this.$store
.dispatch("auth/login", { Username, Password })
.then(() => this.$router.push("/"))
.catch(err => console.log(err));*/
login({ Username, Password }) {
const API_URL = "http://127.0.0.1:8000";
const url = `${API_URL}/auth/login/`;
return axios
.post(url, { Username, Password })
.then(() => this.$router.push("/"))
.catch(err => console.log(err));
}
},
mounted() {
this.login();
}
};
</script>
first, I tried using the auth service but the failure was OPTIONS not POST.
then i used axios directly to post user and get token, but then the failure was method not allowed, I do not know what is the hidden process, can you explain please?
app.vue
<template>
<div id="app">
<navbar v-if="isAuthenticated"></navbar>
<router-view></router-view>
</div>
</template>
<script>
import { mapGetters } from "vuex";
import Navbar from "./components/Navbar";
export default {
name: "app",
components: {
Navbar
},
computed: mapGetters("auth", ["isAuthenticated"])
};
</script>
router.js
import Vue from "vue";
import Router from "vue-router";
import About from "./views/About";
import Home from "./views/Home";
import Login from "./views/Login";
import Lost from "./views/Lost";
import PasswordReset from "./views/PasswordReset";
import PasswordResetConfirm from "./views/PasswordResetConfirm";
import Register from "./views/Register";
import VerifyEmail from "./views/VerifyEmail";
import store from "./store/index";
const requireAuthenticated = (to, from, next) => {
store.dispatch("auth/initialize").then(() => {
if (!store.getters["auth/isAuthenticated"]) {
next("/login");
} else {
next();
}
});
};
const requireUnauthenticated = (to, from, next) => {
store.dispatch("auth/initialize").then(() => {
if (store.getters["auth/isAuthenticated"]) {
next("/home");
} else {
next();
}
});
};
const redirectLogout = (to, from, next) => {
store.dispatch("auth/logout").then(() => next("/login"));
};
Vue.use(Router);
export default new Router({
saveScrollPosition: true,
routes: [
{
path: "/",
redirect: "/home"
},
{
path: "/about",
component: About,
beforeEnter: requireAuthenticated
},
{
path: "/home",
component: Home,
beforeEnter: requireAuthenticated
},
{
path: "/password_reset",
component: PasswordReset
},
{
path: "/password_reset/:uid/:token",
component: PasswordResetConfirm
},
{
path: "/register",
component: Register
},
{
path: "/register/:key",
component: VerifyEmail
},
{
path: "/login",
component: Login,
beforeEnter: requireUnauthenticated
},
{
path: "/logout",
beforeEnter: redirectLogout
},
{
path: "*",
component: Lost
}
]
});
main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";
import axios from "axios";
import Axios from "axios";
import VueAxios from "vue-axios";
import Vuex from "vuex";
Vue.use(Vuex);
Vue.use(VueAxios, axios);
//Vue.config.productionTip = false;
Vue.prototype.$http = Axios;
const token = localStorage.getItem("token");
if (token) {
Vue.prototype.$http.defaults.headers.common["Authorization"] = token;
}
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
references:
https://www.techiediaries.com/vue-axios-tutorial/
https://scotch.io/tutorials/handling-authentication-in-vue-using-vuex
https://github.com/jakemcdermott/vue-django-rest-auth

Most likely CORS issues.
If you're serving the vue server on different port then the django server, then you need to set the proper CORS settings.
Please refer to https://github.com/ottoyiu/django-cors-headers/

while it seems my code is little ugly because I mixed bunch of repositories, but at least I made it make POST successfully. I used
npm install qs
then import it, then:
var username = payload.credential.username;
var password = payload.credential.password;
then editing
axios.post(url, qs.stringify({ username, password })
and it worked.

Related

Attempts with creating authorization to site turns out to: Error POST 404 (OK)

I can't get how to solve problem with POST request.
I am trying implement authorization on my site (via Vuejs,vuex,vue-router, axios).
I will be very pleasure, if you give me some advice.
I searched info on forums , but situation was not the same.
Why 404 (OK)? If OK, why 404?
It means, that server received my data, but can't compare correct this or not?
I have components/pages:
App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home page</router-link> |
<router-link to="/login">Login</router-link>
<span v-if="isLoggedIn"> | <a #click="logout">Logout</a></span>
</div>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
computed : {
isLoggedIn : function(){ return this.$store.getters.isLoggedIn}
},
methods: {
logout: function () {
this.$store.dispatch('logout')
.then(() => {
this.$router.push('/login')
})
}
},
created: function () {
this.http.interceptors.response.use(function (err) {
return new Promise(function (resolve) {
if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
this.$store.dispatch("logout")
resolve()
}
throw err;
});
});
},
}
</script>
LoginAnalytics.vue
Here user must input his mobile phone and password.
<template>
<div>
<form class="login" #submit.prevent="login">
<h1>Sign in</h1>
<label>Mobile</label>
<input required v-model="mobile" type="tel" placeholder="mobile phone"/>
<label>Password</label>
<input required v-model="password" type="password" placeholder="Password"/>
<hr/>
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
export default {
data(){
return {
mobile : "",
password : ""
}
},
methods: {
login: function () {
let login = this.mobile
let password = this.password
this.$store.dispatch('login', { login, password })
.then(() => this.$router.push('/secure'))
.catch(err => console.log(err))
}
}
}
</script>
Vuex store
Here I am creating axios POST requests to server.
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import { API_BASE_URL, TEMPORARY_TOKEN } from '../config';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
trainings: [],
incomings: [],
sources: [],
avgShedule: [],
metro: [],
conversion: [],
avgIncome: [],
status: '',
token: localStorage.getItem('token') || '',
user : {},
},
mutations:{
auth_request(state){
state.status = 'loading'
},
auth_success(state, token, user){
state.status = 'success'
state.token = token
state.user = user
},
auth_error(state){
state.status = 'error'
},
logout(state){
state.status = ''
state.token = ''
},
},
getters:{
isLoggedIn: state => !!state.token,
authStatus: state => state.status,
},
actions:{
login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request')
axios({
url: `${API_BASE_URL}/analytics.auth`,
data: user,
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
})
.then(resp => {
const token = resp.data.token
const user = resp.data.user
localStorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', token, user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
logout({commit}){
return new Promise((resolve) => {
commit('logout')
localStorage.removeItem('token')
delete axios.defaults.headers.common['Authorization']
resolve()
})
}
}
},
)
router.
There all refs to components and pages
import Vue from 'vue'
import Router from 'vue-router'
import store from '#/store'
import Analytics from '#/pages/Analytics-test.vue'
import LoginAnalytics from '#/components/LoginAnalytics.vue'
import HomeAnalytics from '#/components/HomeAnalytics.vue'
Vue.use(Router)
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: HomeAnalytics
},
{
path: '/login',
name: 'login',
component: LoginAnalytics
},
{
path: '/secure',
name: 'secure',
component: Analytics,
meta: {
requiresAuth: true
}
},
]
})
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
export default router
And also main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import store from './store'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = axios;
const token = localStorage.getItem('token')
if (token) {
Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
Every time, when I am try login me with correct mobile and password, I received error like this:
Problem was with mistake in API endpoint.
All times I tried call this url:
url: ${API_BASE_URL}/analytics.auth,
But correct is:
url: ${API_BASE_URL}/account.auth.

vuex error with quasar $store.auth is undefined

I am trying to use vuex with Quasar. I have created an authentication module as below.
// src/store/auth/index.js
import { api } from 'boot/axios';
export default {
state: {
user: null,
},
getters: {
isAuthenticated: state => !!state.user,
StateUser: state => state.user,
},
mutations: {
setUser(state, username){
state.user = username
},
LogOut(state){
state.user = null
},
},
actions: {
LOGIN: ({ commit }, payload) => {
return new Promise((resolve, reject) => {
api
.post(`/api/login`, payload)
.then(({ data, status }) => {
if (status === 200) {
commit('setUser', data.refresh_token)
resolve(true);
}
})
.catch(error => {
reject(error);
});
});
},
}
}
I imported it in the store
// src/store/index.js
import { store } from 'quasar/wrappers'
import { createStore } from 'vuex'
import auth from './auth'
export default store(function (/* { ssrContext } */) {
const Store = createStore({
modules: {
auth:auth
},
// enable strict mode (adds overhead!)
// for dev mode and --debug builds only
strict: process.env.DEBUGGING
})
return Store
})
And I imported it into MainLayout to check if the user is logged in.
// src/layouts/MainLayout
<template>
</template>
<script>
import { ref, onMounted } from 'vue'
import packageInfo from '../../package.json'
import { useStore } from 'vuex'
export default {
name: 'MainLayout',
setup () {
const $store = useStore;
const connected = ref(false);
function checkLogin(){
//console.log($store)
return connected.value = $store.auth.isAuthenticated
};
onMounted(()=> {
checkLogin();
});
return {
appName: packageInfo.productName,
link:ref('dashboard'),
drawer: ref(false),
miniState: ref(true),
checkLogin,
}
}
}
</script>
But every time, I get the same error :
$store.auth is undefined
I tried to follow the quasar documentation, but I can't. Can anyone tell me what I am doing wrong please?
Thank you.
Someone helped me to find the solution. My error is to have written const $store = useStore instead of const $store = useStore(). Thanks

How to keep user logged in between page refreshes in FastAPI and Vue

I am new to vue.js, I have a simple web application(Vue frontend connected to a FastAPI backend) that a user can create an account and login, All of this works so far but when I refresh the page the user is logged out.
And console show an error:
Uncaught (in promise) TypeError: Cannot read property '$store' of undefined
What am I doing wrong? How to keep user logged in even after page refresh. Can anyone please help me?? thanks
store/index.js
import Vuex from 'vuex';
import Vue from 'vue';
import createPersistedState from "vuex-persistedstate";
import auth from './modules/auth';
// Load Vuex
Vue.use(Vuex);
// Create store
const store = new Vuex.Store({
modules: {
auth
},
plugins: [createPersistedState()]
});
export default store
store/modules/auth.js
import { postUserLogInAPI } from "../../service/apis.js";
const state = {
token: "",
expiration: Date.now(),
username: ""
};
const getters = {
getToken: (state) => state.token,
getUsername: (state) => state.username,
getFullname: (state) => state.fullname,
isAuthenticated: (state) => state.token.length > 0 && state.expiration > Date.now()
};
const actions = {
async LogIn({ commit }, model) {
await postUserLogInAPI(model).then(function (response) {
if (response.status == 200) {
commit("LogIn", response.data)
}
})
},
async LogOut({ commit }) {
commit('LogOut')
}
};
const mutations = {
LogIn(state, data) {
state.username = data.username
state.fullname = data.fullname
state.token = data.token
state.expiration = new Date(data.expiration)
},
LogOut(state) {
state.username = ""
state.fullname = ""
state.token = ""
state.expiration = Date.now();
},
};
export default {
state,
getters,
actions,
mutations
};
service/http.js
import axios from 'axios'
import { Loading, Message } from 'element-ui'
import router from '../router/index.js'
import store from '../store';
let loading
function startLoading() {
loading = Loading.service({
lock: true,
text: 'Loading....',
background: 'rgba(0, 0, 0, 0.7)'
})
}
function endLoading() {
loading.close()
}
axios.defaults.withCredentials = true
axios.defaults.baseURL = 'http://0.0.0.0:80/';
axios.interceptors.request.use(
(confing) => {
startLoading()
if (store.getters.isAuthenticated) {
confing.headers.Authorization = "Bearer " + store.getters.getToken
}
return confing
},
(error) => {
return Promise.reject(error)
}
)
axios.interceptors.response.use(
(response) => {
endLoading()
return response
},
(error) => {
Message.error(error.response.data)
endLoading()
const { status } = error.response
if (status === 401) {
Message.error('Please Login')
this.$store.dispatch('LogOut')
router.push('/login')
}
return Promise.reject(error)
}
)
export default axios
components/NavBar.vue
<script>
export default {
name: "NavBar",
computed: {
isLoggedIn: function () {
return this.$store.getters.isAuthenticated;
},
username: function () {
return this.$store.getters.getUsername;
},
fullname: function () {
return this.$store.getters.getFullname;
},
},
methods: {
async logout() {
await this.$store.dispatch("LogOut");
this.$router.push("/login");
},
},
};
</script>

How to access namespaced vuex inside router

i tried to access vuex getters with namespaced modules inside routers.js but the getters always returning null value while the value is true(user logged in)
here is the example code.
store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import auth from './auth'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
auth
}
});
store/auth/index.js
import axios from "axios"
export default {
namespaced: true,
state: {
token: null,
user: null,
status: null
},
getters: {
authenticated(state) {
return state.token && state.user && state.status;
},
user(state) {
return state.user;
}
},
mutations: {
SET_TOKEN(state, token) {
state.token = token;
},
SET_USER(state, data) {
state.user = data;
},
SET_STATUS(state, status) {
state.status = status
}
},
actions: {
async logIn({ dispatch }, data) {
let response = await axios.post('back/in', data);
return dispatch('attemptLogin', response.data.token)
},
async attemptLogin({ commit, state }, token) {
if (token) {
commit('SET_TOKEN', token);
commit('SET_STATUS', true);
}
if (!state) {
return
}
try {
let response = await axios.get('back/me')
commit('SET_USER', response.data.user)
} catch (e) {
commit('SET_USER', null)
commit('SET_TOKEN', null)
commit('SET_STATUS', null);
}
}
},
}
store/subscriber.js
import store from '../store'
import axios from 'axios'
store.subscribe((mutation) => {
switch (mutation.type) {
case 'auth/SET_TOKEN':
if (mutation.payload) {
axios.defaults.headers.common['Authorization'] = `Bearer ${mutation.payload}`;
localStorage.setItem('token', mutation.payload)
} else {
axios.defaults.headers.common['Authorization'] = null;
localStorage.setItem('token')
}
break;
default:
break;
}
})
router.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '../views/Login';
import LoggedInLayout from '../layouts/LoggedInLayout';
import Dashboard from '../views/Dashboard';
import Post from '../views/pages/Post/Index';
import store from '../store'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [
{
title: 'Login Page',
path: '/backend/login',
name: 'login',
component: Login,
meta: {
mustLoggedIn: true
}
},
{
path: '/backend',
component: LoggedInLayout,
children: [
{
title: 'Dashboard',
path: '/backend/dashboard',
name: 'dashboard',
component: Dashboard
},
{
path: '/backend/post',
name: 'post',
component: Post
},
],
meta: {
mustLoggedIn: true
}
},
]
});
router.beforeEach(async (to, from, next) => {
if (to.matched.some(record => record.meta.mustLoggedIn)) {
console.log(store.getters['auth/authenticated']); // and everytime i tried to console log, it always return null
if (!store.getters['auth/authenticated']) {
next({
path: '/backend/login'
})
} else {
next('/backend/dashboard')
}
} else {
next()
}
})
export default router;
app.js
require('./bootstrap');
import Vue from 'vue';
import store from './store';
import router from './router'
import MainApp from './layouts/MainApp.vue'
import axios from 'axios';
require('./store/subscriber')
axios.defaults.baseURL = 'http://127.0.0.1:8000/api/';
store.dispatch('auth/attemptLogin', localStorage.getItem('token'));
new Vue({
router: router,
store,
render: h => h(MainApp)
}).$mount('#app');
and yeah, when i tried to validate if the user is loggedin throught console log always returning null value, and i stuck with this problem for 1 hour already, can anyone help me to solve this problem ?
You are just syncing your store with local-storage. You also need to persist it for it to stay on after reload etc.,
You will need to use something like vuex-persist.
https://www.npmjs.com/package/vuex-persist
Maybe you get error on "back/me" ?
Try to add "consol.error" in the catch block!
However, why login page has meta "mustLoggedIn" setted true ?

Vue Router fails to navigate from inside unit tests using jest

I have a router, Home, Login components and unit tests for the Login component.
The logic is: when user is unauthenticated, send him to Login page, once he's authenticated, send him to home page.
The logic works fine in the browser, however, when I run unit tests, I get an exception: thrown: undefined once the login component tries to navigate using this.$router.push('/');
In the console I see the message:
trying to route /login /
and then the exception is thrown once i run next();
Am I missing some setup to have the router working properly in the test environment?
Alternatively: is there a way to mock the next() function passed to the navigation guard?
Here's the router:
import VueRouter from 'vue-router';
import Home from '#/views/Home.vue';
import Login from '#/views/Login.vue';
import { state } from '#/store';
export const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
noAuthRequired: true,
},
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
router.beforeEach((to: any, from: any, next: any) => {
console.log('trying to route', from.fullPath, to.fullPath);
const isAuthed = !!state.user.token;
if (!to.meta.noAuth && !isAuthed) {
next({ name: 'login' });
} else {
next();
}
});
export default router;
The component (relevant part):
import Vue from 'vue';
import Component from 'vue-class-component';
import { axios } from '../plugins/axios';
#Component
export default class App extends Vue {
private credentials = {
email: '',
password: '',
};
private error = '';
private async login() {
try {
const data = await axios.post('http://localhost:5000/api/v1/user/auth', this.credentials);
const token = data.data.payload;
this.$store.dispatch('setUser', { token });
this.error = '';
this.$router.push('/');
} catch (error) {
console.warn(error);
this.error = error;
}
}
}
And the unit test:
import Vue from 'vue';
import Vuetify from 'vuetify';
import AxiosMockAdapter from 'axios-mock-adapter';
import { Wrapper, shallowMount, createLocalVue } from '#vue/test-utils';
import flushPromises from 'flush-promises';
import Vuex, { Store } from 'vuex';
import { axios } from '#/plugins/axios';
import VTest from '#/plugins/directive-test';
import LoginPage from '#/views/Login.vue';
import { mainStore, state, IState } from '#/store';
import VueRouter from 'vue-router';
import router from '#/router';
describe('Login page tests', () => {
let page: Wrapper<Vue>;
let localStore: Store<IState>;
const localVue = createLocalVue();
const maxios = new AxiosMockAdapter(axios);
const vuetify = new Vuetify();
const errorMessage = 'Input payload validation failed';
const emailError = 'Invalid Email format';
const validData = {
email: 'valid#email.com',
password: 'test pass',
};
// in order for "click" action to submit the form,
// the v-btn component must be stubbed out with an HTML button
const VBtn = {
template: '<button type="submit"/>',
};
localVue.use(Vuetify);
localVue.directive('test', VTest);
localVue.use(Vuex);
localVue.use(VueRouter);
beforeAll(() => {
maxios.onPost().reply((body: any) => {
const jsonData = JSON.parse(body.data);
if (jsonData.email !== validData.email) {
return [400, {
message: errorMessage,
errors: { email: emailError },
}];
}
return [200, { payload: 'valid-token' }];
});
});
beforeEach(() => {
try {
localStore = new Vuex.Store({
...mainStore,
state: JSON.parse(JSON.stringify(state)),
});
page = shallowMount(LoginPage, {
store: localStore,
router,
localVue,
vuetify,
stubs: {
VBtn,
},
attachToDocument: true,
sync: false,
});
} catch (error) {
console.warn(error);
}
});
afterEach(() => {
maxios.resetHistory();
page.destroy();
});
const submitLoginForm = async (data: any) => {
page.find('[test-id="LoginEmailField"]').vm.$emit('input', data.email);
page.find('[test-id="LoginPasswordField"]').vm.$emit('input', data.password);
page.find('[test-id="LoginBtn"]').trigger('click');
await flushPromises();
};
it('Redirects user to home page after successful auth', async () => {
await submitLoginForm(validData);
expect(page.vm.$route.path).toEqual('/');
});
});