Unable to execute V-model unit tests accurately

I've been puzzling over why I can't seem to successfully test a V-model and what mistake I might be making. Here's my straightforward component:

<template>
  <p>Hello counter!! {{ modelValue }}</p>
  <button type="button" @click="buttonClicked">Click me</button>
</template>

<script lang="ts">
export default {
  props: {
    modelValue: {
      type: Number,
      default: 0,
    },
  },
  emits: ["update:modelValue"],
  methods: {
    buttonClicked() {
      console.log("button clicked!!!");
      this.value = this.value + 1;
    },
  },
  computed: {
    value: {
      get() {
        return this.modelValue;
      },
      async set(value: any) {
        console.log("Passing!!!");
        this.$emit("update:modelValue", value);
      },
    },
  },
};
</script>

And here's the test scenario I have in place:

import { nextTick } from "vue";
import { describe, it, expect } from "vitest";
import CounterView from "../CounterView.vue";

describe("CounterView", () => {
  it("should update v-model correctly", async () => {
    let modelValue = 12;
    const wrapper = shallowMount(CounterView, {
      props: {
        modelValue,
      },
    });

    const button = wrapper.find<HTMLElement>("button");

    await button.element.click();

    await nextTick();

    expect(modelValue).toBe(13);
    expect(wrapper.vm.$props.modelValue).toBe(13);
  });
});

Unfortunately, neither of these assertions are yielding the desired outcome:

  • expect(modelValue).toBe(13);
  • expect(wrapper.vm.$props.modelValue).toBe(13);
 FAIL  components/__tests__/CounterView.spec.ts > CounterView > should update v-model properly
AssertionError: expected 12 to be 13 // Object.is equality
 ❯ components/__tests__/CounterView.spec.ts:22:42
     20|
     21|     // expect(modelValue).toBe(13);
     22|     expect(wrapper.vm.$props.modelValue).toBe(13);
       |                                          ^
     23|   });
     24| }

  - Expected   "13"
  + Received   "12"

What am I missing or doing incorrectly?

Answer №1

Thank you for your help! I realized my mistake and now I've set up a parent component to test properly.

<-- Testing CounterView Component -->

import { mount } from "@vue/test-utils";
import { describe, it, expect } from "vitest";
import ParentView from "../ParentView.vue";
import CounterView from "../CounterView.vue";

describe("CounterView", () => {
  it("should update v-model correctly", async () => {
    const wrapper = mount(ParentView, {});

    const parent = wrapper.findComponent(CounterView);

    expect(wrapper.html()).toMatchSnapshot();
    expect(parent.html()).toMatchSnapshot();

    await parent.find<HTMLButtonElement>("button").trigger("click");
    expect(wrapper.vm.$data.counter).toBe(25);

    expect(wrapper.html()).toMatchSnapshot();
  });
});

<-- Displaying Parent View -->

<template>
  <div>
    <CounterView v-model="counter"></CounterView>
  </div>
  `, }
</template>

<script lang="ts">
import CounterView from "./CounterView.vue";

export default {
  components: {
    CounterView,
  },
  data() {
    return {
      counter: 24,
    };
  },
};
</script>

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

Unable to retrieve a random element from an array in Angular 10

I'm attempting to shuffle items (cards that have English words) from a flashCards array, so that each card can appear randomly when the user reloads the page. I tried using the Math.floor(Math.random()) function, but it's not working. How can I r ...

The behavior of K6 test execution capabilities

Hey there, I'm new to K6 and I've got a query about how tests are executed. Take this small test with a given configuration for example: export const options = { stages: [ { target: 10, duration: '30s'} ]} When I run the test with ...

Error encountered when uploading an image using an inertiajs form.post in Laravel 8 due to failed mime image validation

Laravel version: 8.82.0 When using inertiajs, I am facing an issue while uploading an image through a post request using the form.post method. The controller receives image data as shown in the image below: https://i.sstatic.net/pMFTu.png This is my sim ...

Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a pers ...

Angular's Validator directive offers powerful validation capabilities for reactive forms

Referenced from: This is the approach I have experimented with: custom-validator.directive.ts import { Directive } from '@angular/core'; import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms'; @Directive({ ...

Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code: await page.getByRole('button', { name: '3 Employees' }).click(); The problem is that the button's name fluctuates based on the number of employees, causing ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...

Adjusting the information of a fresh element within an array will subsequently impact all other elements within

I have a problem with my Angular application where I need to add new elements to an array. The array is shown on the GUI after clicking a button. Here is how my current array looks: [ {name: 'user1', percentage: '1'} ] But after click ...

Tips for playing a video uploaded directly into Vue-plyr

My attempt to integrate vue-plyr with a YouTube video was successful using the following code: <template> <section id="vision" class="vision"> <vue-plyr> <div data-plyr-provider="youtube" data- ...

Click on an element in Angular to toggle it

A function in my codebase is responsible for toggling a specific section within a div element. Currently, there are a total of 3 sections available in the app. The functionality is implemented in the app.component.ts file: show = false; toggle() { ...

Rejecting the request by clicking a button

While switching to a menu, I retrieve data from the API. As the pending data is still loading in DevTools, I click on the Filter button to search for additional data. The data I am searching for appears in my table. However, once the pending data finishes ...

Angular TypeScript Directive Link function not being executed

I've been working on implementing a Role-Based-Access-Control system in my application. The allowed resources are loaded from the server after login, and I was able to verify this using raw JavaScript code. angular.module('app').directive(& ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

How to Retrieve Error Message from Response in Django REST Framework When Making a 400 Bad Request

I have a setup where I'm using Vue with DRF for my application. Whenever there is an issue with the form data and it is sent to the API, it responds with a 400 Bad request error as expected. The response in the Network tab provides a clear validation ...

Employing monaco-editor alongside typescript without webpack within an electron endeavor

I need help incorporating the monaco-editor into my electron project built with TypeScript. Using npm install -D monaco-editor, I installed it successfully and imported it with import { editor } from "monaco-editor";. Despite not receiving any mo ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Cypress lacks the capability to activate functions that have been included using document.addEventListener during a keypress event

In my React application, I have implemented an event listener on the document that responds to the left and right arrow key presses. While manually triggering the event by pressing the keys in Cypress open-ct works fine, attempting to trigger it programma ...

What are the steps to update my vue-cli global installation to the newest version available?

Vue-cli 3.5.5 is already installed on my system. Upon running vue create myapp, I receive a message stating Update available 3.6.2. Vue CLI v3.5.5 ┌───────────────────────────┐ │ Update availabl ...

Navigate through Angular 2 array elements

I am facing an issue where I have an array and I need to display only a single object from the array at a time. The goal is to cycle through the array using a button, but I'm struggling to figure out how to display just one object at a time. You can s ...