Troubleshooting: Issues with updating a text field in Vue test utils using Jest

Hello, I am new to Jest and unit testing. I have a question about how to set the value of a text input using Vue Test Utils.

Here is the code for my custom text input component:

<input
    v-model="local_value"
    @keyup.enter="submitToParent"
    :class="input_class"
    :id="id"
    :disabled="is_disabled"
    :maxlength="max_length"
    :placeholder="placeholder"
    :autocomplete="(is_autocomplete) ? 'on' : 'off'"
    :name="id"
    :ref="id"
  />

Here is the test code I have written:

it("typing on the field should update the value correctly", async () => {
        const wrapper = shallowMount(TextInput, {
            propsData: {
                id: "my_input",
            }
        })

        // Find the component (which works properly), then try to insert some text
        const input = wrapper.findComponent({ref: "my_input"})
        input.element.value = "sample text"
        input.setValue("sample text")

        // The value still remains an empty string (""). Not sure what's going wrong.
        console.log(wrapper.vm.local_value)
        expect(wrapper.vm.local_value).toBe("sample text")


If you have any solutions to this problem, please let me know. Thank you for your time.

Answer №1

In my understanding, the setValue function operates asynchronously, which means you may have to use

await input.setValue('sample text')
to ensure proper execution.

Answer №2

When setting the value of vm's local_value, be sure to do it this way:

const wrapper = shallowMount(TextInput)
await wrapper.setData({
   local_value: 'sample text'
})

If local_value is declared in data(), or:

const wrapper = shallowMount(TextInput)
await wrapper.setProps({
   local_value: 'sample text'
})

If local_value is declared in props() within your component.

Afterward, verify it with:

expect(wrapper.vm.local_value).toBe('sample text')

Note that this only checks the vm value, not the rendered value on the DOM.

To include testing the rendered value, you need to first declare the property value in your component for testing purposes:

<input
    v-model="local_value"
    // ... rest of the properties
    :value="local_value"
/>

Then test it using:

const input = await wrapper.findComponent({ ref: "my_input" })
expect(input.attributes('value').toBe('sample text')

An ideal test scenario would resemble:

it('should have input value' async () => {
  const wrapper = shallowMount(TextInput)
  await wrapper.setProps({  local_value: 'sample text' })
  
  const input = await wrapper.findComponent({ ref: 'my_input' })
  expect(wrapper.vm.local_value).toBe('sample text')
  expect(input.attributes('value').toBe('sample text')
})

👍 Quick tip:

To check the rendered input attributes, comment out all expect statements and insert:

expect(input.attributes('').toBe('random chars here to force an error')

The console will then display errors with the expected attribute output.

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

Ways to segregate Vue functionality within a Laravel application using distinct layout and page templates

I am currently working on a Laravel application with a Vue instance connected to the body tag (or a div within the body). const app = new Vue({ el: '#app' }); I believe it would be beneficial to utilize the Vue instance for managing aspects ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

Trouble with integrating HTML5 canvas from an external JavaScript file

Having trouble with storing canvas js in an external file. If the javascript responsible for drawing on the canvas is included in the html header, then the rectangle is displayed correctly. Here is the working html (javascript in html header): <!DOCT ...

Displaying an HTML button above JavaScript code

Hello, I am currently working on a project that involves displaying the Earth and I am in need of assistance with positioning some buttons on the screen. Currently, I am facing an issue where the buttons appear either above or below the JavaScript code. I ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Signing off from GitHub Packages for npm

As I work on a project that utilizes a private GitHub package, I have been using it locally with the command npm login --registry=https://npm.pkg.github.com. However, this approach has posed problems when attempting to deploy the project in a production en ...

Struggling with retrieving data from a file in Angular service while using node-webkit. Unable to make it functional

I've been struggling for a while and gone through numerous solutions, but I can't seem to figure out why this code isn't functioning: I have a requirement to pass data between controllers, so I created a service, right? (The data is coming ...

Using JSON parsing to extract an integer as the key in JavaScript

I've been searching for almost 2 hours now, but I can't seem to find anyone using an integer as the key in their json object. The structure of my json object is as follows: {"342227492064425": {"added":"2020-10-04T23: ...

When the remove button is pressed, I want the checkbox to become unchecked

I need help with unchecking a checkbox after confirming the removal of items. Can someone provide guidance on how to achieve this? Below is the code I am using: JavaScript: $(".rem-btn").click(function(){ var remConf = confirm("Are you sure you ...

What are some strategies for incorporating emotional themes into unit tests?

When testing certain components, it is necessary to pass a theme for accurate results, either through the emotion ThemeProvider or withTheme API. A similar issue was encountered with 'styled-components', as discussed here. According to VladimirP ...

Formik Alert: Update depth limit reached

Currently, I am working on an EDIT formik form that is displayed as a MODAL. The issue arises when the setState function is triggered with setState(true), causing the form to appear without any onClick event. Despite changing onClick={editStory} to onClick ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Error: JSON input ended unexpectedly and was not caught in the promise block

This code snippet showcases the add to cart functionality, which involves inserting data into a database. Although the database insertion works correctly, an error occurs every time the "add to cart" button is clicked (despite still successfully adding to ...

Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea: contact_list.vue <template lang="pug"> .table .table-header.table-row .table-col Contact .table-col Info .tabl ...

Resetting md-radio-button choices within an Angular 2 application

My Angular app has a sorting filter using radio buttons via md-radio-group for users to choose how they want data displayed. The radio buttons work fine, but I'm struggling to clear them when the "Restore Defaults" button is clicked. This is the code ...

Trouble with passing data from action to reducer in Redux with React Native

As a newcomer to Redux, I'm encountering an issue while trying to make an API call in the Action and pass the data to the reducer. Although I can see the response from the API call, there seems to be a problem with sharing the data correctly with the ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...