Vue appears to be having trouble waiting for the axios Post request

While testing a login request, I encountered an issue where jest did not call the mock:

This is my test :

const User = '123123'

jest.mock('axios', () => ({
  get: jest.fn(),
  post: (_url, _body) => new Promise((resolve, reject) => {
    if (_body.username != User) return reject({ data: { auth: false } })
    resolve({
      data: {
        auth: true,
        data: '123456789789213',
        name: 'Indra'
      }
    })
  })
}))

describe('Component', () => {
  let actions
  let store

  beforeEach(() => {
    actions = {
      logIn: jest.fn()
    }
    store = new Vuex.Store({
      actions
    })
  })
test('Logins in server', () => {
    const wrapper = shallowMount(Login, { store, localVue })

    const inputLogin = wrapper.find('[name=login]')
    const inputPassword = wrapper.find('[name=password]')

    //fake user and password
    inputLogin.element.value = User
    inputPassword.element.value = 'Indra1234'

    wrapper.find('button').trigger('click')
    expect(actions.logIn).toHaveBeenCalled()
  })
})

And here is the login function:

methods : {
        AuthUser () {
            if(this.server == "Select a server") return this.$swal('Attention', 'Please select a server!', 'error');
            console.log("Requesting login")
            this.loading = true
            try {
                axios.post(this.server+"/auth",
                {
                    username: this.id,
                    password: this.password
                })
                .then(result => {
                    console.log(result)
                    if(result.data.auth) {
                        this.tk = result.data.data
                        this.nome = result.data.name
                        this.logIn
                        setTimeout(() => {
                            console.log("Hi")
                            $("body, this").css("background-color","#FBF5F3");
                            // this.$router.push('/home')
                            this.$eventHub.$emit('logIn', 1);
                        }, 1000);

                    } else {
                        this.loading = false
                        this.$swal('Attention', 'Incorrect username or password!', 'warning');
                    }
                }).catch((er) => {
                    this.loading = false
                    this.$swal('Sorry', 'A communication error with the server occurred!', 'error');
                    console.log(er)
                })
            } catch (error) {
                this.loading = false
                this.$swal('Sorry', 'An error occurred while logging in', 'error');
                console.log('Internal Error: ', error)
            }

        }
    }

When running the test, it can be seen that the console log "Requesting login" is being called. The test configurations were set up using Vue CLI 3 and I referred to for guidance.

Answer №1

It appears that the promises are not being flushed properly. Have you considered using the flush promise library?

npm i --save-dev flush-promises

and then...

// at the top of your file
import flushPromises from 'flush-promises';

//...
    wrapper.find('button').trigger('click');
    await flushPromises();
    expect(actions.logIn).toHaveBeenCalled();

For more information, check out: https://vue-test-utils.vuejs.org/guides/testing-async-components.html

Answer №2

The issue arose when attempting to set the input values.

Upon logging console.log(wrapper.vm.id, wrapper.vm.password), both appeared as null.

To address this problem:

    inputLogin.element.value = User
    inputLogin.trigger('input');
    inputPassword.element.value = 'Indra1234'
    inputPassword.trigger('input');

Additionally, ensure to include flushPromises() as well.

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

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Does anyone know of a way to integrate a calendar feature into a React application using a library

Greetings to everyone, I trust you are all enjoying a fantastic day. I am in search of an interactive calendar similar to this one for one of my applications Does anyone know of a React library that could assist me in creating such a feature? ...

Discovering an Element in jQuery through its ID using Spaces and Variables

My issue involves locating an element within another element using an ID and then adding a class when the ID is hardcoded. For example: var tableId = el.id; $('#' + tableId).find("[id='Checkout On']").addClass('highlight'); ...

VueJS 3 custom Checkbox fails to update UI upon clicking

I'm attempting to implement a customized checkbox using Vue 3 and the composition API based on this example. However, despite confirming through devtools that all my props and bound data are successfully passed from the parent component to the child c ...

Top method for filling an array with strings

Imagine having an array called 'newArray'. var newArray = []; You can add strings to it like this: var thisString = 'watch'; newArray.push(thisString); Now, if you want to have 50 instances of the 'thisString' in the newAr ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

What methods can I use to prevent repeated login requests to SalesForce databases when using Express.js routers?

Is there a way to avoid logging into SalesForce databases and passing queries on multiple routers in express.js? It's tedious to login every time. If you have any suggestions, please let me know. var conn = new jsforce.Connection({ oauth2 : salesfo ...

When running the "react-scripts build" command and then serving it, the HTML files are being served instead

After successfully generating the build folder using react-scripts and running npm run build, I attempted to serve it locally with the npm package called serve by running serve -s build. The serve command started running on port 5000 without any issues. ...

What is the proper way to structure the DATETIME format when making an API request to mySQL?

Frontend code: import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; ... Backend code: //set up express server const express = require("express"); const app ...

Implementing a JSON query with an onkeyup event listener

My main objective with this code is to trigger a json query request by using a textfield to specify the location. It's essentially a quick search feature that searches for specific content on a different website. For example, if I input www.calsolum/ ...

The server sends a Status=304 response to one browser's GET request, while providing a 200 response to another browser's request

My focus right now is on troubleshooting my .htaccess file, in which I have the following code: <FilesMatch "\.(html|swf)$"> <IfModule mod_headers.c> Header set Cache-Control "no-cache, public" </IfModule&g ...

Issues with Vue-select dropdown functionality are causing inefficiencies

I am utilizing vue-select to generate a standard drop-down menu. However, it comes with a search bar by default that I do not need and prefer to keep it simple. I attempted to hide the search bar by using "display: none" which made it disappear. This is t ...

Can we pass a search term parameter to getServerSideProps in Next.js?

I've been working on a project to organize all my notes and summaries in one place. The notes are stored as markdown files, converted to HTML dynamically in the backend (it's functioning well). Now, I want to add a search feature on the notes p ...

What is the functionality of require(../) in node.js?

When encountering var foo=require(../), what specific modules does node.js search for? It may appear to look in the directory above the current one, but what exactly is it seeking and how does it function? Is there a comparison with include in C or impor ...

Tips for effectively retrieving data from the server in Node.js

When attempting to retrieve data using /data with server-side fetch, I encountered the following errors: response.getCategory is not a function (()=>{ const url = "/data"; fetch(url) .then(response => { console ...

What is the best method for accessing the service response data when I am sending back an array of custom map with a promise as an object?

Sharing my code snippet below: function createObject(title, array){ this.title = title; this.array = array; } //$scope.objects is an array of objects function mapPromise(title, promise){ this.title= title; this.promise = promise; }; var fet ...

What is the procedure for iterating through the square brackets of a JSON array?

Here's the data I have: $json_data_array = '[ { "id": 1, "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd7cdffcbdacccb91dcd0d2">[email protected]</a>", ...

Send an ajax request to upload several images to the server

I am currently facing an issue with my web application that allows users to create posts with a maximum of 15 images. I have implemented AJAX requests to send all the data, including the images, in one request. However, I encountered this error: An error ...

What is the best way to access the value of a child element using $event within AngularJS?

Utilizing $event.currentTarget to access the element on ng-click: <div ng-click="eventHandler($event)" class="bg-master m-b-10" id="slider-tooltips" nouislider=""></div> Upon inspecting my controller&apo ...

Error occurred due to an unexpected end of JSON input following a pending promise

I am currently developing a data handler that requires downloading a file for parsing and processing within the handler. To handle this, I have implemented the file request within a promise and called it asynchronously from other methods. Including the h ...