Issue encountered while executing unit test for Vue web application

I am currently developing a web application using VueJs and attempting to set up unit tests for it. I took inspiration from the unit-tests in vue-mdl. However, I am encountering difficulties as the tests are not running properly for my code. The issue arises when I try to access vm.$el, which returns undefined, hindering my progress.

Below is the component that I am trying to test:

Confirmation.vue

<template>
    <div>
        Your order has been confirmed with the following details.
    </div>
</template>

<script type="text/javascript">
export default {
  data () {
    return {
      data_from_pg: null
    }
  }
}
</script>

Here is the failing test for the component:

Confirmation.spec.js

import Confirmation from 'src/components/Confirmation'
import { vueTest } from '../../utils'

describe('Confirmation', () => {
  let vm
  let confirmation
  before(() => {
    vm = vueTest(Confirmation)
    console.log('vm.$el ' + vm.$el) => this prints undefined
    confirmation = vm.$el.querySelector('#confirmation') => so this line gives error
    // confirmation = vm.$('#confirmation')
  })

  it('exists', () => {
    confirmation.should.exist
    confirmation.should.be.visible
  })
})

utils.js

export function vueTest (Component) {
  const Class = Vue.extend(Component)
  Class.prototype.$ = function (selector) {
    return this.$el.querySelector(selector)
  }
  Class.prototype.nextTick = function () {
    return new Promise((resolve) => {
      this.$nextTick(resolve)
    })
  }

  const vm = new Class({
    replace: false,
    el: 'body'
  })

  return vm
}

You can find the complete code here, along with all the test configurations that I have attempted to modify multiple times without success. If you spot any errors or have any suggestions on how to resolve the issue, please do let me know. Thank you.

Answer №1

Utilizing the vueTest function in utils aims to inject the Vue instance into the body tag:

const vm = new Class({
  replace: false,
  el: 'body'
})
return vm

When conducting unit tests, it is vital to load individual components rather than index.html as an entry point. Consequently, accessing document or html elements becomes unfeasible and mounting the component is consequently hindered. It would be advised to employ vm.$mount():

If elementOrSelector argument is not provided, the template will be rendered as an off-document element.

The code above could be modified as shown below:

const vm = new Class();
vm.$mount();
return vm;

This adjustment will grant your tests access to the $el property.

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

The CodeIgniter's input->post() returns null when using jQuery to make an AJAX POST request

I am encountering an issue where, despite setting a unique identifier for each row in my database-populated table, the ID value is not being passed correctly to PHP when attempting to delete a row. I have implemented a data-id attribute on each row's ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Data-id attribute fails to appear when applied to an element hidden with display:none property

Creating a notification popup feature using bootstrap popover. Each notification is represented by a div with the same classes, but different text content. <% Loop through notifications and create a div for each %> <div class="media n-media n ...

Error: Attempting to access property 'toLocaleLowerCase' of an undefined value

I've been working on a custom pipe following the instructions carefully, but I keep encountering an error when trying to filter my list. Below is the code for my custom pipe: import { Pipe, PipeTransform } from '@angular/core' ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

Different ways to make jQuery attr() method include the attribute by using single quotation marks

I start by creating a div in memory: var video_div = document.createElement('div'); video_div.className = "vidinfo-inline"; Next, I define some variables: var key = "data-video-srcs"; var value = '{"video1":"http://www.youtube.com/watch?v ...

Checking for partial matches in JavaScript using includes()

I've encountered a problem while comparing a string of numbers to ids in a JSON file using JavaScript to generate a favorites list. I'm utilizing the includes() method to check if the tourid in the JSON file matches any of the numbers in the stri ...

What is the process for initiating a state transition?

I have created two separate components. One component uses v-navigation-drawer, while the other component contains a button that toggles the state of the v-navigation-drawer using vuex. On smaller screens, when clicking on the gray area to close the navig ...

What is the process of converting a value from an HTML form into a PHP variable?

I am looking to update the order preparation time. I have created an HTML form, but I am facing issues passing it into a PHP variable after this code block. I have tried using Cookies and POST method, but neither has helped me so far. <form> ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Unable to retrieve JSON data for the JavaScript object

I have been working on creating a JS object in the following manner var eleDetailsTop = new Array(); var j = 0; var id = "ele"+j; eleDetailsTop[id] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image& ...

Adapting website content in real-time based on the information stored in a MySQL

Looking to update my website dynamically based on a value from the MySQL database in real-time. I currently have some code that partially achieves this functionality, but it seems to fail after a few calls by randomly switching between two values. I have ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

When you start scrolling down, the JavaScript menu will cleverly disappear, only to re

I am facing an issue with my menu, which is a normal block-displayed div. There is another div with annotation above it. I want the menu to stick to the top as fixed when scrolling down, but immediately hide itself. The goal is for the menu to appear when ...

Accessing local storage in HTML 5 using Selenium

I have been working with Selenium web driver in C# and I encountered a weird issue. When I use a JavaScript method to write to local storage, it works perfectly fine (I can see the values when inspecting the HTML page), but when I try to read from the loca ...

Steps for converting JSON into a structured indexed array

My goal is to efficiently convert the data retrieved from my firebase database into a format suitable for use with a SectionList. I have successfully established a part of the data structure, but I am facing challenges in associating the data correctly. ...

Is the security of "the fate of browser gaming" a concern?

It is predicted that HTML5 will be widely used for game design, but the question remains: how can security be ensured in online HTML5 games? Consider a scenario where players earn badges in a platform game by completing difficult levels. Upon winning a ba ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Tips on how to ensure a JAVA application opens a webpage in a designated browser

Adding the microsoft-edge prefix to a URL (microsoft-edge:) will open the page in Edge, regardless of the browser being used for running the app. I am wondering if there is an equivalent prefix for Chrome and Firefox? Thank you in advance. ...

Extract data from JSON in Google Sheets

UPDATE: entry.content.$t is actually not the correct field to access individual cells. The proper method is using entry.gsx$[cell column header]. Thank you for pointing out this mistake and assisting in finding a solution. Initial inquiry: I am currently ...