In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element search, trigger, NextTick, vuelidate error return. However, I am encountering a problem in updating the DOM in the second test and subsequent tests within the describe() block after the trigger. While the first test waits patiently for await NextTick() and the validator+vuetify adds classes to the label element, the same code does not behave as expected in the second identical test.

If you could provide insight into why the identical code cannot be repeated in the second test, I would greatly appreciate it. Thank you. P.S. My stack includes VUE + VUETIFY + JEST.

import { mount } from '@vue/test-utils'
import 'babel-polyfill';
import Vue from "vue";
import Router from 'vue-router';
import store from "~/store";
import types from '~/store/types'
import util from '~/util'
import i18n from '~/i18n'
import Client from '~/service/Client'
import Login from '~/views/Login'
import Vuetify from 'vuetify'
import Snotify from 'vue-snotify'
import storage from '~/storage'
import config from '~/config'
import inflection from 'inflection'
import Vuelidate from 'vuelidate'

Vue.config.productionTip = false;
Vue.prototype.$storage = storage;
Vue.prototype.$config = config;
Vue.prototype.$inflection = inflection;
Vue.use(Vuelidate);
Vue.use(Snotify);
Vue.use(Client);
Vue.use(util);
Vue.use(Vuetify);
Vue.use(Router);

describe("Validate login form", () => {

  const route = {
    path: '/login',
    meta: {
      public: true,
    }
  };

  const r = new Router({
    base: '/',
    mode: 'history', // hash
    linkActiveClass: 'active',
    routes: [route]
  });

  const errors = ['error--text'];

  const factory = (values = {}) => {

    return mount(Login, {
      types,
      r,
      i18n,
      store,
      data () {
        return {
          ...values
        }
      }
    })
  };

  it("first it", async () => {

    const wrapper = factory({ email: "" }); // new instance with data

    wrapper.find(".v-btn--block").trigger("click"); // success firing
    await wrapper.vm.$nextTick();
    expect(wrapper.html()).toMatchSnapshot()

    // expect( wrapper.vm.$v.email.$error ).toBe(true); // ok true

    // DOM updated
    expect ( wrapper.find("label[for='email']").classes() ).toEqual(expect.arrayContaining(errors)); // ok true - classes containing error class

  });

  it("second it", async () => {

    const wrapper = factory({ email: "" }); // new instance with data

    wrapper.find(".v-btn--block").trigger("click"); // success firing
    await wrapper.vm.$nextTick();
    expect(wrapper.html()).toMatchSnapshot();

    // expect( wrapper.vm.$v.email.$error ).toBe(true); // ok true

    // DOM not updated
    expect ( wrapper.find("label[for='email']").classes() ).toEqual(expect.arrayContaining(errors)); // bad false - classes do not containing error class

  });

});

Answer №1

It is important to properly clean up the mounted component after each test. One way to do this is by using the beforeEach() method:

describe("Checking the login form", () => {
  // ...
  let wrapper;
  beforeEach(() => {
    wrapper = mount(Login, {
      types,
      r,
      i18n,
      store,
      data () {
          return {
          ...values
          }
      }
      })
  });
// ...

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

Is it possible for asynchronous functions to write to the same object concurrently and result in invalid values?

I have been experimenting with the code below to see if it can cause any issues with the integer i in the object context. My tests so far have not revealed any problems. // Node.js (v10.19.0) const Promise = require('promise') // object access ...

Discover the latest version of Vue with the powerful Vuex 4 integration

I'm currently utilizing Vue 3 along with the composition API and I'm exploring the best way to directly map my state from Vuex so that the template can easily access and update it using v-model. Is mapState the solution to this issue, or is ther ...

Node.js exporting fails due to an undefined variable

When attempting to export variables in Node.js, I keep receiving an undefined error. I'm not sure what the issue is, can anyone provide assistance or suggestions? Here is a snippet from index.js: var test = 10; module.exports.test = test; And here i ...

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Utilizing Nuxt for local import of the client exclusively

I recently came across VuePlyr and decided to integrate it into my Nuxt 2 project. Initially, I got it working by setting it up as a plugin in /plugins/vue-plyr.js, import Vue from 'vue' import VuePlyr from '@skjnldsv/vue-plyr' import & ...

React-select: issue with maintaining selected option on input

Hello everyone, I am new to React and seeking some assistance in reviewing my code. I have a component called Bucket that contains multiple challenges as separate components. Here is a simplified version of the code: class CLL_Bucket extends Component { ...

What is the process for incorporating a class into a table within TinyMCE using JavaScript?

I am facing an issue with adding a class to a table. I'd like the following code: <table></table> to transform into this code by clicking a button in tinymce. <table class="try-class"></table> I have added a button, bu ...

Exploring the connection between the App.vue file and other components within a Vue.js webpack setup

I set up vuejs using webpack as my bundler. vue init webpack frontend In the main.js file, I implemented vue-router with the following routes: routes: [ { path: '/', name: 'Home', component: HomeView }, This is ...

Securing Vue.js Routing with API and JWT Tokens: My Approach

I am currently working on developing an application using Adonis.js for the API and Vue.js for the front-end. To ensure security for all API routes, I have implemented JWT token authentication. I recognize the significance of utilizing JWT to safeguard AP ...

Updating route from action within Vuex Store

Exploring ways to trigger a route change from the store. I attempted to import router directly into the store and use the following code: LOG_OUT({commit}){ commit('LOG_OUT__MUTATION'); router.push({ name: 'Login' }) } Unfo ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Summary in Javascript

After utilizing the inspect code tool in PHPStorm, I received the following message: 'recipient_user.id === app.currentUser.id ? true : false' can be simplified to '!!(recipient_user.id === app.currentUser.id)' I'm wondering: ...

What could be causing the excessive number of entries in my mapping results?

I am in need of mapping an array consisting of dates. Each date within this array is associated with a group of dates (formatted as an array). For instance: The format array looks like this: let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10] ...

Change locale in Vue with Vue-i18n

Consider the following code: <ul> <li v-for="(lang, i) in $i18n.availableLocales" :key="`Lang${i}`" :value="lang"> <a href="#" @click="setLocale('what should be placed here?')" ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

What is the most effective method for determining if an object contains a particular property?

Can anyone advise on the best approach to check if an ajax response object has a specific property? I've done some research and it seems there are various methods to do this. One way is: if(ajaxResponse.hasOwnProperty('someProperty')){ ...