What are the steps for assigning data to this.$root while testing a VueJS component?

VueJS 2.4 allows us to access root data from a component using this.$root. An example of this can be seen in the following JSFiddle:

https://jsfiddle.net/bjg2yL1u/1/

By clicking on a button, you will see 'orange' displayed in the console, which is a root data not owned by the triggering todo-item.

I am currently conducting a Jasmine test which is running properly and showing green results.

However, the console.log inside the todo-item component is outputting 'undefined'.

The question arises, how can I inject data into this.$root instance while inside a test?

describe("TodoItem", function() {

  var sut;
  var message = {text:'word'}

  beforeEach(function() {
    var Constructor = Vue.extend(TodoItem);
    sut = new Constructor({
      propsData: {
        todo: message,
      }
    }).$mount();
  });

  it("Should be able to reverse the given word", function() {
    // Given
    expect(sut.todo.text).toEqual('word');
    expect($(sut.$el).find('li').text()).toEqual('word');

    //When
    sut.reverseMessage();

    // We encounter a problem here with 'undefined' being printed, because there is nothing attached to this.$root when within a test        

    // Then
    expect(sut.todo.text).toEqual('drow');

  });
});

Answer №1

When setting up a Vue instance from an extended component as shown below:

var Constructor = Vue.extend(TodoItem);
sut = new Constructor({
  propsData: {
    todo: message,
  }
}).$mount();

In this scenario, Constructor essentially acts as the $root. It is important to note that there is no display_light property defined within your TodoItem component. Therefore, when attempting to log this property using console.log, it will display undefined.

To include the data property in the component and ensure your test functions correctly (although not recommended), you can follow this approach:

var Constructor = Vue.extend(TodoItem);
sut = new Constructor({
  propsData: {
    todo: {text: "hello world"},
  },
  data(){
    return {
      display_light: 'orange'
    }
  }
}).$mount();

You can view the updated version of your code in this updated fiddle.

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

Setting up 'ngProgress' as a loader in my project using the 'ngbp boilerplate' is straightforward and easily customizable

Currently, I am utilizing the 'ngbp' angular boilerplate from GitHub to develop my project. My goal is to implement ngProgress for displaying a loader when navigating between sections. I have successfully installed ngProgress via bower and ensur ...

Unit tests for Jasmine show that $compile generates comments when using ng-repeat

Can anyone explain why this code snippet: var scope = $rootScope.$new(); dump($compile('<ul><li ng-repeat="item in [1,3,5,7,9]">{{item}}</li></ul>')(scope)); generates the following output: '<ul class="ng-scope" ...

The API is invoked twice

I have developed an app centered around hockey statistics. However, I am facing a challenge with the endpoints as I only have access to team and player stats. My current approach involves calling the API with the first team, selecting the top 2 players, ...

Changing the destination URL containing a hash using Next JS

In my project built with Next.js, I am facing a challenge where I need to set up a redirect for URLs containing the character "#" symbol. For instance, when a user visits /contact#support, I want it to automatically redirect to /contact-us/support First ...

Utilize Javascript in Django to fetch information from database values

Seeking guidance as a newcomer to Django. Utilizing datatables (https://datatables.net/) to display my database data, but facing issues with data not appearing in the table. Any suggestions on what modifications need to be made in my code? views.py from ...

Changing images upon hovering with preloading

I'm looking to enhance my logo listing with a hover effect that switches the logo from color to black and white. Here's the current markup I have: var sourceToggle = function () { v ...

Leveraging kubectl.exe in conjunction with Docker and Node.js

I am currently attempting to execute my kubectl.exe file within a Docker environment. The version of kubectl is 1.26.2 and the Kustomize version is v4.5.7. Running everything successfully locally with npm start, however when trying in a docker container, ...

The drag and drop feature in Webdriver is failing to function properly on the w3schools website

Attempting to use the dragAndDrop method of Actions is not functioning properly on the w3schools website: However, the same code works flawlessly on another page. Below is the code that was tested: WebDriver driver = new FirefoxDriver(); driver.get("htt ...

The re-rendering in vue.js is not as accurate as that of the vue instance object

Hey there! I'm facing a minor issue with my vue template. Here's the code snippet that's causing the trouble: <template> <div class="panel panel-default" v-bind:id="'panel_'+noeud.id"> <div class="panel-hea ...

Shifting image from center to corner as you scroll

Hello there, I'm new to this so please bear with me for any obvious mistakes, thank you :) My goal is to have an image move from the center of the screen to the corner of the screen as you start scrolling. I've made some progress on this, but I& ...

Utilize JavaScript or jQuery to align a list item center on a horizontal scrolling navigation bar

Currently, I am utilizing bootstrap 4.6 for a webpage, and while the default navbar doesn't meet my requirements for mobile navigation, I am attempting to customize it to function like MODE_SCROLLABLE in Android. Therefore, I need it to activate the l ...

Behat fails to function properly with Selenium 2.33 when using the "When I press..." command

I am in the process of creating a test to log in to my local website. I have written a test feature using Behat: Feature: User Login Test In order to access my account As a registered user I want to successfully log in @javascript Scenar ...

Error 403 occurs after submitting the form

Recently, I encountered a 403 error when attempting to submit the form on this page. Interestingly, when I directly accessed the new page by typing the URL into my browser, it loaded without any issues. The PHP code in the initial page looks like this: & ...

How to redirect PHP with header location and passing parameters

Currently, I am using a redirect link to move from a landing page to an offer page. However, I want to include a redirect page in between that is customized based on the parameters I provide. For example, my URL looks like this: http://domain.com/file.php ...

Update Table Row Background Color in Separate Table by Clicking Button Using JQuery

Two tables are involved in this scenario - one that receives dynamically added rows, and another that stores the data to be included. The illustration above displays these tables. Upon clicking the Edit button, the information from the selected row in Tab ...

Revise the content within the table cell

Running the following code using server push: $('tr[name=' + device + ']').find("td[id='status']").text('STARTED'); When attempting to access the element's id, it returns the correct value. $('tr[name=& ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

Mapping Service by Google - Navigate from your current location to desired destination

I have a script that currently displays a route for either car or transit depending on the user's selection. I am looking to adapt this script to set the origin as the user's current location and route from there to a set latitudes and longitudes ...

Prevent Xdebug from processing multiple requests

One recurring issue I encounter in my app is calling an API endpoint every 60 seconds. However, when I attempt to debug using Xdebug, stepping through the controller associated with that endpoint often takes longer than a minute. This results in another re ...

JavaScript code for displaying and concealing elements

I have a simple requirement where I need to check for a variable and display or hide a class based on its value. This is being done on a SharePoint publishing page. The snippet below is not working as expected: if (source === 'show') { $(&a ...