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

Cannot access array method(s) using MyObject.prototype.reduce callback

As I delve into prototyping, I encountered an issue with using forEach and reduce on my ArraySet prototype. The arrow function callback works well with forEach, but I hit a roadblock with reduce. It seems the notation that works for a normal Array doesn&ap ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

What methods and technologies are accessible for executing JavaScript through PHP?

Are there any frameworks or tools available to execute JavaScript from PHP? Is there a similar project like the Harmony project for PHP? I am interested in running JS unit tests (or even BDD) directly from PHP, as demonstrated in this post (for Ruby). Am ...

Request a HTML variable and send it to JavaScript

My latest project involves a Binary to Decimal Calculator that is now fully functional, but I am looking to integrate an HTML input into it. <html> <input placeholder="00000000" name="htmlinput"></input> <input id="clickMe" type="butt ...

Manipulating prop values through dropdown selection

I'm currently working on implementing filtering based on a prop value that changes according to the dropdown selection. Here's my progress so far: template(v-for="field in tableFields") th(:id="field.name") select(@change="filterScope(sc ...

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

Modify the color of the selected row in the v-data-table

I am trying to customize the background color of the selected row in a v-data-table. <v-data-table dense :headers="headers" :items="records" @click:row="handleClick"> <!-- handleClick is a function that lo ...

JavaScript - Error encountered when accessing information from elements in the DOM

Just started learning javascript and encountering a problem that I can't seem to solve. I'm attempting to assign the className of a <div> element to a variable, but I keep receiving this error message: scripts.js:30 Uncaught TypeError: Can ...

Separating Vue.js 2 - taking out the HTML snippet from a single file component and placing it in its own

I was pondering if there is a method to divide a Single File Components file into smaller segments. What do I mean by this? Let's take a look: <template> ... </template> <script> export default { name: 'my-component&a ...

How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example: var someJsonArray = [ {point: 100, level: 3}, {point: 100, level: 3}, {point: 300, level: 6} ]; At times, it may have a different combination lik ...

Javascript code has been implemented to save changes and address resizing problems

Code Snippet: <script> function showMe(){ document.querySelector('#change').style.display = ''; document.querySelector('#keep').style.display = 'none' document.querySelector('#change1').style.d ...

How come my countdown application functions properly when accessed through the browser via the HTML page, but encounters issues when utilized with an HTTP server?

I have encountered an issue where the app functions correctly when I open the HTML file in my browser, but fails to load the CSS and JavaScript when accessing it through localhost:3000. HTML: <html> <head> <link href="./main.css" rel="st ...

Progress bar carousel component based on advancement movements

Here is the mockup I am working with: https://i.sstatic.net/bIepQ.png So far, I have made good progress with this code: https://codesandbox.io/s/codepen-with-react-forked-16t6rv?file=/src/components/TrendingNFTs.js However, I am facing a couple of challe ...

What is the best way to empty a TextField in a React application?

Greetings to all! I could use some help figuring out how to clear a TextField after clicking the icon. Any suggestions would be greatly appreciated. Thanks! const [filteredLocations, setFilteredLocations] = useState(locations); const clearSearch = () =& ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

Making modifications to the CSS within an embedded iframe webpage

Assigned with the task of implementing a specific method on a SharePoint 2013 site. Let's dive in. Situation: - Within a page on a SharePoint 2013 site, there is a "content editor" web part that displays a page from the same domain/site collection. T ...

Revamp the sequence of divs using jQuery

<div class="example first">111</div> <div class="example second">222</div> <div class="example third">333</div> Can the order of these divs be changed using jQuery? I am looking to get: <div class="example second"&g ...

I seem to be having an issue with the decimal point on my calculator - I only want to see one dot

Only need one dot for the calculator to function properly. The current situation with multiple dots is causing confusion. I intend to address other aspects of the code later, but I'm currently struggling with this issue. function dec(d) { let ...