The button is functioning properly, however, the unit test is indicating an issue

I have implemented a button on the page that increments a counter when clicked:

<template>
    <div>
        <span id='count'>{{count}}</span>
        <button @click="increment">+</button>

    </div>
</template>
<script>
    export default {
        data() {
            return {
                count: 10,
            }
        },
        methods: {
            increment() {
                this.count++;
            }
        }
    }
</script>

However, my unit test is failing to detect the change in the count after clicking the button. Is there an error in my unit test causing it to report the wrong result?

import { expect } from 'chai';
import { mount } from '@vue/test-utils';

import Counter from '@/components/Counter';

describe('test::::', () => {
    it('test1:::', () => {
        const wrapper = mount(Counter);
        expect(wrapper.find('#count').text()).to.be.equal('10');
        wrapper.find('button').trigger('click');
        expect(wrapper.find('#count').text()).to.be.equal('11');
    });
});

Error message:

AssertionError: expected '10' to equal '11'

Answer №1

The problem arises when the assertion is made before the changes from the click handler are applied.

By utilizing the trigger() method, a Promise is returned which resolves after the component has been updated. To address this issue in testing, you can make the test callback function async, and then utilize await with the trigger() function:

it('test1:::', async () => {
   //...
   await wrapper.find('button').trigger('click');
   expect(wrapper.find('#count').text()).to.be.equal('11');
});

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

The reason behind Node.js using 7 threads per process

Upon starting a Node.js process, the top command displays 7 threads connected to the process. What exactly are these threads responsible for? Furthermore, as the workload on the API rises and request handlers start asynchronously waiting for other upstre ...

What is the functionality of CKEditor 5 in Next.JS?

I encountered the following problem: Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your c ...

I am encountering an issue where the JSON data is not being properly loaded into my Angular 8 application

Here is the structure of my JSON data: { "content": [ { "id": 1, "name": "test name", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbfaeb8bf8bbfaeb8bfe5a8a4a6"&g ...

React's memo feature continues to render even if the component's props have not undergone

I am facing an issue with a stateless functional component that relies on React context for its content. Despite using React.memo() to optimize performance, the component keeps re-rendering when there are no changes in props or context. I have verified thi ...

An External Force is Disrupting My Jquery

Something seems off because everything was working perfectly fine until the FallingLeavesChristmas.min.js file stopped activating on this specific page. I initially thought it was an issue with the JavaScript itself, but that doesn't seem to be the ca ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Interactive dropdown menu feature created with CSS and JavaScript

Currently, I am working on establishing a cohesive style for a compact web form. An issue that has arisen is the difficulty in customizing the dropdown list to match the desired aesthetic - it seems like the browser scroll options and other elements are d ...

Employing condition-based require() statements in JavaScript

I am currently experimenting with conditionally loading modules that are Vue components. Review the code snippet below for a better understanding: index.js My goal is to dynamically load different components based on the window URL (since I cannot use vu ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...

Utilizing AJAX to update form data using a JavaScript function

On my HTML page, I have an AJAX submit script that loads a PHP script containing a form with just one input field for comments. This form is submitted via AJAX using the POST method. Now, I am looking to create a JavaScript function that can be triggered ...

Combine the values of a second array in Javascript when the corresponding values in the first array are equal

Apologies if the title is a bit unclear. Explaining the concept of multiple arrays is a challenge for me. Consider the following array: [ [21, 1000], [21, 500], [18, 100], [18, 200] ] My goal is to obtain the resulting array: [ [21, 1500], [18, 300] ] H ...

Adjusting the size of the parent element for a ThreeJS renderer

Is there a way to display a fixed 550 x 500 container inside a table for a 3D object without changing the parent container's size when calling container.appendChild(renderer.domElement);? Any suggestions on how to resolve this issue? HTML: <t ...

Unveiling the mystery of Google's invisible reCAPTCHA integration with WordPress and utilizing Ajax

Trying to integrate Google Invisible reCaptcha into a custom submit form using submit.js (ajax) has been a successful endeavor thanks to the guidance provided in this helpful tutorial on implementing the new Invisible reCaptcha from Google. However, when ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

Transforming BufferGeometry to Geometry using FBXLoader within the Three.js library

Check out my snippet below for loading a .fbx object. It defaults to loading an object as BufferGeometry: const loader = new THREE.FBXLoader(); async function loadFiles(scene, props) { const { files, path, childName, fn } = props; if (index > fi ...

The function vue.findIndex is not recognized as a valid function

Encountered an issue with the findIndex() function Uncaught (in promise) TypeError: state.carts.findIndex is not a function The cartId includes rowId, qty, sizeVal, and image Methods updateCart() { this.$store.dispatch('updateCart&apos ...

The color of the three js cube is charcoal, definitely not a fiery red

Just dipping my toes into the world of three.js...my cube is displaying in black even though I set the color to red. Any ideas why? <!DOCTYPE html> <html> <head> <title>Experimenting with shapes</title> & ...

What is the method of aligning content to the left side in a slick slider?

My slider is set up to display three elements, but I'm having trouble aligning one or two elements to the left instead of centering them. jQuery(function () { jQuery('.slider-blog').slick({ arrows: false, dots: true, ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

performing an AJAX request to the controller method in a Rails application

I am currently facing an issue with making an ajax call to my controller class PatientRecordController < ApplicationController def export .... end end Within my javascript file, the code snippet is as follows: $(document).ready(function(){ ...