Unit test failing due to Vue v-model binding not functioning as expected

I am attempting to monitor the value of the #username element when I change the data in form.username

// Regitser.vue

...
<div class="form-group">
  <label for="username">Username</label>
    <input type="text"
           class="form-control"
           id="username"
           v-model="form.username" />
</div>

...

<script>
export default {
    name: "RegisterPage",
    data: function() {
        return {
            form: {
                username: "",
                emailAddress: "",
                password: ""
            }
        };
    }
};
</script>

This is a sample code snippet

// Test 
describe("RegisterPage.vue", () => {
    let wrapper;
    let fieldUsername;
    let fieldEmailAddress;
    let fieldPassword;
    let buttonSubmit;

    beforeEach(() => {
        wrapper = mount(RegisterPage);
        fieldUsername = wrapper.find("#username");
        fieldEmailAddress = wrapper.find("#emailAddress");
        fieldPassword = wrapper.find("#password");
        buttonSubmit = wrapper.find('form button[type="submit"]');
    });

    it("should have form inputs bound with data model", () => {
        const username = "sunny";
        const emailAddress = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8cbcdd6d6c1f8ccd9cbd3d9dfd1d4dd96dbd7d5">[email protected]</a>";
        const password = "VueJsRocks!";

        wrapper.vm.form.username = username;
        wrapper.vm.form.emailAddress = emailAddress;
        wrapper.vm.form.password = password;
        expect(fieldUsername.element.value).toEqual(username);
        expect(fieldEmailAddress.element.value).toEqual(emailAddress);
        expect(fieldPassword.element.value).toEqual(password);
    });

Upon running the test, it failed

// Test failed
RegisterPage.vue › should have form inputs bound with data model

    expect(received).toEqual(expected) // deep equality

    Expected: "sunny"
    Received: ""

      52 |         console.log(wrapper.find("#username").element.value);
      53 | 
    > 54 |         expect(fieldUsername.element.value).toEqual(username);
         |                                             ^
      55 |         expect(fieldEmailAddress.element.value).toEqual(emailAddress);
      56 |         expect(fieldPassword.element.value).toEqual(password);
      57 |     });

      at Object.<anonymous> (tests/unit/RegisterPage.spec.js:54:45)

I input 'sunny' in form.username but the element did not change. How can I resolve this issue?

Answer №1

Arriving here a bit behind schedule, I found myself encountering the same issue while following along with the book 'Building Applications with Spring 5 with VueJS 2'. The issue stemmed from the book's reliance on older versions of Vue and vue-utils. If you had used the package.json file from the book's repository, things would have likely worked smoothly.

However, for those of us using the latest Vue CLI, we ended up in this situation! @Estradiaz's comment was indeed spot on. Below is the modified test:

it('should have form inputs bound with data model', async () => {
  const username = 'sunny'
  const emailAddress = 'sunny@local'
  const password = 'VueJsRocks'
  await wrapper.setData({
    form: {
      username: username,
      emailAddress: emailAddress,
      password: password
    }
  });
  expect(fieldUsername.element.value).toEqual(username)
  expect(fieldEmailAddress.element.value).toEqual(emailAddress)
  expect(fieldPassword.element.value).toEqual(password)
})

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

Obtaining an OBJECT from a hashmap instead of a string

In my code, I am working with a hashmap and I want to extract all the values from this map without needing to reference a specific key. Here is a basic overview of the process: Create a hashmap using an external file with a structure of "id:value" Utili ...

Text color wave effect - mimic a block of colors flowing through text

I'm experimenting with creating a unique text effect where, upon hovering over the text, it appears as though a block of color is passing through it. Inspired by the technique showcased in this first example (specifically for the word "Kukuri"), I ut ...

Utilizing browser local storage in web development

Currently, I am in the midst of working on an e-commerce platform, a project that holds significant importance for me as it marks my debut into major projects. For the first time, I am delving into the realm of local storage to manage basket data such as q ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

Having trouble retrieving image using "image-to-base-64" in react?

Utilizing the package "image-to-base64" for converting images from URLs to base64 is resulting in an error when attempting to fetch images: TypeError: Failed to fetch at imageToBase64Browser (browser.js:11:1) at convertImage (mealPlanTablePDF.tsx:2 ...

Alternative techniques apart from submitting

Within my PHP submit form, I have integrated a PHP image gallery that pulls images from a specific folder (with a dropdown to select images from different folders). When I click on an image in the gallery, the path to that image is automatically entered i ...

Having trouble getting Video.js SWF to work on Internet Explorer?

I've been working with video.js and am having trouble getting it to function properly on Internet Explorer. I have added the swf file like this: videojs.options.flash.swf = "http://vjs.zencdn.net/4.2/video-js.swf " Here is the code for the video pla ...

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

What is the best way to ensure the parent element adjusts to fit its floated children, without exceeding the width of the window?

I am attempting to center a group of floating elements, but due to them being displayed in masonry style, I cannot set them as inline. It is clear that a container is necessary, but I have been unable to find information on how to achieve this: Please dis ...

Is the Positioning of JS Scripts in Pug and Jade Documents Important?

Have you ever wondered why a page loads faster when certain lines are placed at the end of the tag instead of inside it? script(src="/Scripts/jquery.timeago.js") This phenomenon is often seen in code like this: //Jade file with JQuery !!! 5 html(lang=" ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays - const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; Initializing Arrays - const matches1 = []; const matches2 = []; const unmatches1 = []; Array Matching Process - for (const line of source) { const line2Match = target.fi ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

Is there a way to send multiple parameters in an array to a route?

I am working on deleting multiple rows from a MySQL database using checkboxes in my ejs view with node.js and React app. I have successfully deleted a single row, but I am struggling to figure out how to pass an array of parameters for deleting multiple ro ...

Unable to capture mistakes in function executed within try-catch statement

I'm currently facing challenges with implementing asynchronous functions in a Node.js server. This is my first experience working with try/catch blocks and I'm strugging to catch errors within the called function. Here's an excerpt of my co ...

Laravel and x-editable team up to combat integrity constraint violation error code 1048, indicating no data being passed

Utilizing x-editable to generate an editable form that makes ajax requests. The form is structured as follows: <a href="#" class="editable editable-click" id="mileage" data-name="mileage" data-ty ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...