Evaluating Vue.js Watchers using Jasmine

I want to write a test for a VueJS watcher method, in order to verify if it's being called. The watcher method in my component is structured like this:

watch: {
   value: (newValue, oldValue) => {
     if (newValue.Status === 'Completed') {
        ...do something
     }
  }
}

The watcher method triggers successfully when the value changes, however, it doesn't seem to be triggered during the test.

This is how my test code looks like:

var propsData = {
   "value" : {
      "Status" : "Something"
    }
}
it('should call the method', done => {
   const Constructor = Vue.extend(App);
   const spy = sinon.spy(App, 'value');
   const vm = new Constructor({ propsData: propsData }).$mount();
   vm.value.Status = 'Completed';
   Vue.nextTick(() => {
      expect(spy.called).to.be.true;
      done()
   })
})

I have come across some examples that could be helpful, but they haven't quite solved my issue:

  1. Asserting Asynchronous Updates
  2. Forum

Answer №1

Remember, when you modify value.Status, you're actually not changing the reference of value. If you want the watch to trigger on a change in value, make sure to set deep: true.

watch: {
   value: {
     handler: (newValue, oldValue) {
       this.checkValue() 
     },
     deep: true
   }
},
methods: {
  checkValue() {
  }
}

Next, include the following code snippet:

it('should execute method', done => {
   const Constructor = Vue.extend(App);
   const vm = new Constructor({ propsData: propsData }).$mount();
   const spy = sinon.spy(vm, 'checkValue');
   vm.value.Status = 'Updated value';
   vm.$nextTick(() => {
      expect(spy.called).to.be.true;
      done()
   })
})

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 error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Ensuring no null objects are present in the jQuery each function

In order to iterate through each key value pair in a JSON element and display it, I am encountering an issue where some of the keys have null values. As a result, using $.each is throwing an error: TypeError: obj is null I do not want to remove the null ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Double the Trouble: jQuery AJAX Making Two Calls

I've already posted a question about this, but I have now identified the exact issue. Now, I am seeking a solution for it :) Below is my code snippet: $('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax&apos ...

The JavaScript code is failing to retrieve the longitude and latitude of the location on a mobile browser

I am having an issue with my Javascript code not properly retrieving the longitude and latitude from the mobile Chrome browser. While this code works fine on laptop or desktop browsers, it seems to be failing on mobile devices: <script> if (nav ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

Is Firebug a necessary tool for the functioning of my website?

I'm currently tackling a new project that involves complex javascript development. Unfortunately, I am unable to share any code specifics at this time. Initially, my script functioned correctly in Firefox 3.0 but encountered issues when tested on Fir ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

Having trouble with PHP's json_decode function with GET variables in an object?

I am currently working with an angular code that utilizes jsonp. One issue I am encountering is related to the object variable 'o_params' in my params. Here is the javascript code snippet: $http({ method: 'JSONP', ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Modifying an object's attribute in React.js by toggling a checkbox

As I delve into learning React, I am constructing a straightforward todo list. Here's the object contained within my initialState: getInitialState:function(){ return { items: [ { text:"Buy Fish", ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...