Exploring the functionality of Vue.js through Jasmine without the use of JavaScript modules

My task involves investigating unit testing for JavaScript on an older application that does not utilize JS modules (import/export). The app contains JS object/prototypes in external .js files that are imported via script src, and more recently, some Vue 2 components in .vue files using PHP include('mycomponent.vue').

All the available examples for different unit testing frameworks assume the usage of JS modules. Can Vue be effectively tested without modules?

I am feeling a bit overwhelmed and would greatly appreciate any guidance, suggestions, or code samples related to testing.

Thank you for your assistance. It means a lot.

Below is a snippet of a sample component:

PHP view (.phtml)

<?php include 'mycomponent.vue' ?>

<script type="text/javascript">
    Vue.use(Vuex);
    Vue.use(BootstrapVue);
    Vue.component('v-select', VueSelect.VueSelect);

    const i18n = new VueI18n({
        locale: 'en',
        dateTimeFormats: {
            en: {
                long: {
                    year: 'numeric', month: 'long', day: 'numeric',
                    hour: 'numeric', minute: 'numeric',
                    timezone: 'EST',
                },
            },
        },
        messages: {
            en: <?= json_encode([
                'messages' => 'etc'
            ]) ?>,
        }
    });

    const store = new Vuex.Store({
        state: {
            //etc
        }
    });

    new Vue({
        el: '#wrapper',
        store,
        i18n,
        data() {
            return <?= json_encode([
                'something' = [
                bits: 'Bob'
                ]
            ]) ?>;
        },
    });
</script>

<div id="wrapper" v-cloak>
    <mycomponent
        :something="something"
    ></mycomponent>
</div>

mycomponent.vue

<template id="mycomponent_tmpl">
  <div>
    {{currentMessage}}
  </div>
</template>



<script>
Vue.component('mycomponent', {
  template: '#mycomponent_tmpl',

  props: {
    something: {
      type: Object,
      required: true,
    }
  },

  data() {
    return {
        this.message = 'Hello World'
    }
  },

  created() {
    
  },

  mounted() {

  },

  watch: {

  },

  computed: {
    currentMessage() {
        return this.message + ' ' + this.something.bits;
    }
  },

  methods: {
    
  }
});
</script>

Answer №1

After some exploration, I managed to find a solution to my own query in this scenario. My experience might benefit others who are integrating Vue.js into a legacy application and need to conduct testing. While not flawless, the challenge lies in calling methods within the tests that do not seem to update the outerHTML as expected. However, when inspecting the Vue instance in the browser console, the outerHTML does reflect the updates. I am still figuring out how to access these changes during the testing phase, but at least I have made a decent start.

hello-world.vue

<template id="hello_world_tmpl">
  <div>{{getMessage}}</div>
</template>

<script>
Vue.component('HelloWorld', {
  template: '#hello_world_tmpl',
  props: {
    message: {
      type: String,
      required: true,
    }
  },
  data() {
    return {
      msg: this.message
    };
  },
  computed: {
    getMessage() {
      return this.msg;
    }
  },
  methods: {
    newMessage(msg) {
      this.msg = msg;
    }
  }
});
</script>

I utilized PHP include within the Jasmine SpecRunner to incorporate the Vue file

Spec file

it('HelloWorld should not be null', function() {
    let vm = new Vue({
        template: `<HelloWorld message="Hi There!"></HelloWorld>`
    }).$mount();

    expect('<div>Hi There!</div>').toEqual(vm.$el.outerHTML);

    vm.$children[0].newMessage('Test');
    expect('Test').toEqual(vm.$children[0].msg);
});

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

What might be causing certain ajax buttons to malfunction?

There are 5 buttons displayed here and they are all functioning correctly. <button type="submit" id="submit_button1">Img1</button> <button type="submit" id="submit_button2">Img2</button> <button type="submit" id="submit_button3" ...

Why does everything seem to move in sync with the table's scrolling?

I recently had an issue resolved that fixed most of my concerns: I needed to make three separate edits, and now when I reintroduce the other two edits, they are included within the table section and scroll along with the table instead of being stuck beneat ...

Using async/await to handle the callback function

Here is a function that saves a user in the database: exports.saveUser = ({ first_name, last_name, email, password }) => { const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *"; ...

Exchange of Fusion Chart

Attempting to perform a fusion chart swap with asp has proven to be challenging. The alternative approach involves rendering the fusion chart first and then using onmousedown to replace the chart with an image. However, this method is also encountering i ...

Communication with child processes in node.js is not done using the child_process module

Hello Everyone, I'm currently experimenting with node.js to utilize JS plugins developed by others using the child_process API. However, I'm facing an issue where the child process is not able to communicate effectively with the parent process. ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

Renew The Dining Surface

I am looking for a way to update the table content without refreshing the entire page. I am using HTML, CSS, and JavaScript to display the current data from my sqlite3 database. Any tips on how to achieve this would be appreciated. ...

What could be causing PHP to fail to send form scores to the PHP MyAdmin database?

I recently ventured into web development and took on a college project website where I built a form in HTML containing various radio button questions. To handle the validation of answers against the correct ones, I utilized JavaScript. With some assistance ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Determine if the start_date is greater than the end_date using jQuery

Having a particular issue with date validation. The start_date and end_date are obtained from an HTML form, being chosen using a bootstrap date picker. A sample of the dates looks like this: start_date = 15-06-2016 end_date = 14-06-2016 To verify if th ...

Preventing commits when encountering build or lint errors

Every git repository contains git hooks within the .git/hooks directory. I have included a npm run lint command in the pre-commit git hook. However, I am unable to prevent the commit if npm run lint returns an error. ...

"Error: React dotenv is unable to access the .env configuration file

My React and Node project has a .env file in the root directory, along with other important files like .eslint and .gitignore. The .env file contains 6 lines of code such as APIKEY=aeofiunoief, without any special symbols. Within the src/ directory, there ...

Issue with Vue @Watch not properly recognizing changes in a boolean value

I'm currently experimenting with watch functions in vue-ts. I have configured a watch function that is supposed to trigger whenever a Boolean variable's value changes, but for some reason, it's not triggering at all and I'm unable to de ...

Utilize the search component multiple times within a single template in Vue.js

I have a regular search input that searches and displays results effectively. Now, I need to duplicate this search input and reuse it within the same component. <input class="search ml-2" type="search" placeholder="Search" v-model="search"> Here is ...

Using jQuery to alter hover color using a dynamic color picker

I'm looking to update the hover color using a color picker tool. Here are the methods I've attempted: // Initial Attempt $("input[type=color]").change(function(e) { var selectedColor = e.target.value; // $("body").css("background-color ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Real-time JQuery search with instant results

While utilizing a custom script to display search results on the page, I encountered an issue when typing long sentences. Each request goes to the server, resulting in delayed responses that stack up and cause the div to change quickly. This is not the des ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...