Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario?

Method:

close(event) {
  const element = !!event?.target?.closest('#target')

  if (!element) {
    this.isVisible = false
  }
},

Jest test:

it('should change visibility to false if element is false', () => {
    const wrapper = shallowMount(AccountLogin, { mocks })
    wrapper.vm.close()

    expect(wrapper.vm.$data.isVisible).toBe(false)
  })

Answer №1

When the change() event occurs on the main element of your component, you can use this code:

jest.spyOn(wrapper, 'closest')
    .mockImplementationOnce(() => true)

wrapper.vm.close()
expect(wrapper.vm.$data.isVisible).toBe(false)

If the event is triggered on a child element within the main component, you will have to specify that child in the spyOn function and mock its closest method instead of the main wrapper. For example:

jest.spyOn(wrapper.find('input'), 'closest')
    .mockImplementationOnce(() => true)
// ...

The reason for finding the exact element is because jsdom does not fully replicate the actual DOM behavior and events do not bubble up.


What the above script accomplishes: it intercepts the .closest() method of the target element so that it returns true.
This action will result in

!!event?.target?.closest('#target')

returning true, which leads to execution of this.isVisible = true.

To ensure that this.isVisible remains false when #target cannot be found, create a second test with a .closest() mock returning

false</code. Verify that <code>isVisible
does not change from false to true after calling .close(). It's best to trust that the HTML functions correctly rather than extensively testing it.

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

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

The scrollbar remains visible on mobile devices

I'm attempting to remove the scrollbar from all elements in my Vue + Vite application. I do not want to disable scrolling, just hide the scrollbar itself. To achieve this, I have employed the following code snippet. *::-webkit-scrollbar { display: ...

From JSON to PNG in one simple step with Fabric.js

I am looking for a way to generate PNG thumbnails from saved stringified JSON data obtained from fabric.js. Currently, I store the JSON data in a database after saving it from the canvas. However, now I want to create a gallery of PNG thumbnails using thi ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

vue.js and the various elements that make up its architecture

My component content is not appearing!!! I have checked the router multiple times and it seems to be functioning correctly, but when I run the project, the components are empty. Even though I have added a lot of content to them, they appear to be blank. ...

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

What is the best way to trigger a JavaScript onclick event for a button that is located within a dropdown menu on an HTML page

I've implemented a feature that resizes the font size within a text area based on the selected font size. It was functioning flawlessly... until I decided to place the font size selection in a drop-down menu, which caused the feature to stop working. ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

Switching the default port for a Vue.js application running in a Docker container

I am currently in the process of changing the default port for a Vue.js app running on docker. I have experimented with both examples provided in the official documentation, which can be found here. For instance, I have a Dockerfile using http-server: FR ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

The AJAX request for JSON data is functioning correctly in Firefox, but is experiencing compatibility issues with other web browsers

I recently completed a PHP page that generates a valid JSON document. The jQuery code used to fetch and display the data is quite straightforward: $.ajax({ url: "http://localhost:8888/rkm/json-jc", dataType: "json", success: function(data) { ...

The troubleshooting of a find method in Mongoose

Why is it necessary to use await twice when calling the model function, even though we already used await in the model itself: async function model() { return await data.find({}, '-_id -__v') } When I console.log await data.find({}, '-_id ...

Bypassing redirection in Nuxt for seamless login experience

I've been exploring ways to implement authentication on my Nuxt app, but I'm struggling to find a tutorial that doesn't rely on redirecting to public or private paths. For example: if (user.isLoggedIn()) { redirect('/dashboard&apo ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

Where is the function returned by redux-thunk invoked?

Can you help me understand where the function returned by addUser is being called in this action creator and redux thunk function? const userAdded = () => ({ type: types.ADD_USER, }); export const addUser = (user) => { return function (dispat ...

The useStarRating() hook continues to display 0 even after the user has interacted with the star component

I've created a custom useStarRating hook to manage the state of a star rating component in my React project. Everything seems to be working properly, but I'm facing an issue with retrieving the updated value of currentValue after the user interac ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...