Having trouble passing arguments to button methods in jasmine when applying vue and moment libraries

I am working on unit testing a Vue app using `jasmine` and `karma`. Here is an example of the code inside one of my components:

After fetching data from a database with `v-for=(data,index)`, I am displaying the `data.date` in the template:

<p class="date">
  {{ dateFilter(data.date) }}
</p>

I want to test if the date is being properly formatted. In my spec file, I have something like this:

import { mount } from '@vue/test-utils';
import moment from 'moment'

it('should call method', () => {
  const selector = wrapper.find('date');
 
});

How can I call the method and provide mock parameters for testing? Also, is it possible to import moment.js in our tests?

Answer №1

In order to verify if the date is displayed in the correct format:

const wrapper = mount(MyComponent, {
  propsData: {
    // suppose the component has a `items` prop, utilized in:
    // <p class="date" v-for="data in items"> {{ dateFilter(data.date) }} </p>
    items: [
      {
        id: 100,
        date: new Date('2020-12-10T12:30:45-08:00') // 12:30pm GMT-8 === 4:30pm UTC
      }
    ]
  }
})

const dateEl = wrapper.find('.date') // locate first dateElement with `date` class
expect(dateEl.text()).toEqual('16:30 pm')

To directly test the component method, access the method via the vm property of the wrapper:

expect(wrapper.vm.dataFilter(new Date('2020-12-10T12:30:45-08:00'))).toEqual('16:30 pm')

Answer №2

It's advisable to avoid using a method in this scenario and opt for a computed property instead

computed: {
    dateFilter() {
      return moment.unix(this.data.date).utc().format("HH:mm a");
    },
}

within the template

<p class="date">
      {{ dateFilter }}
 </p>

You can now modify the data.date value in the test (presumably passed as a prop)

import { mount } from '@vue/test-utils';
import moment from 'moment'

const wrapper = mount(YourComponent)


 it('should call method', () => {

      const localThis = { date: <date-here> }
      expect(wrapper.computed.numbers.call(localThis)).toBe(<experct-result-here>)
 
  });

UPDATE

To tackle the issue of needing to pass arguments when iterating elements, the recommended Vue approach is to create a component e.g. and implement the logic there. It could accept a data prop and function like this:

Parent.vue
<display-date v-for="(data,index)in allData" :key="data.id||index" :data-prop="data" />

Inside the display-date component, you can apply the previously suggested logic. Keep in mind the significant differences between computed properties and methods.

Happy coding!

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

Update the total in the input field by aggregating data from multiple input fields in a Vue2 component

When receiving a response from an API, I am generating a variable number of input fields for product quantity. Each input field takes a number as input and I need to update the total price for each item and the subtotal for all items when the user changes ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

Modify a unique custom binding handler in such a way that it is designated using an Immediately Invoked Function Expression

I am currently working on improving a custom binding handler by converting it into an Immediately Invoked Function Expression (IIFE). Despite researching IIFE online, I am still unsure of how to make the necessary changes to my custom handler. Can someon ...

Convert a JSON array into a new format

Here is the JSON data input provided: "rows": [ [ 1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement" ], [ 2, "ADM ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Is it possible for the versions in the package.json file to be altered

I've made updates to my package.json file - all packages are listed as follows: "dependencies": { "@apollo/client": "3.6.4", "bootstrap": "4.6.2", "graphql": "16.5.0" } ...

An unexpected error occurred in the Ember route processing: Assertion Failed in the listing

After working diligently to integrate an Emberjs front end (utilizing Ember Data) with my Flask API backend, I have encountered a puzzling issue. Despite the adapter functioning correctly - as evidenced by the API being called when accessing the 'List ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

Encountered an unfamiliar custom element: x while utilizing Buefy

Following the Buefy guidelines, I took the necessary steps. First, I ran: npm install Buefy Next, in my main.ts file, I imported Vue, Buefy, axios, and VueAxios like so: import Vue from 'vue'; import Buefy from 'buefy'; import axio ...

Applying CSS styles to a page depending on certain conditions

Currently, I have a page in SharePoint that can function as a pop-up. I am using JavaScript to identify whether it is a pop-up by checking if window.location.search.match("[?&]IsDlg=1"). However, I am struggling to figure out how to insert CSS based on ...

React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded? I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set withou ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

Is JQuery the ultimate solution for creating a dynamic multi-language website?

Embarking on a new project that requires support for multiple languages. My plan is to create a jQuery/AJAX based application with all the code in jQuery, simply calling JSONs for data. What would be the most effective approach for implementing multi-lan ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Modifying HTML line codes using Python: A step-by-step guide

If only I could modify this particular line: <button _ngcontent-c19="" class="blue-button-disabled" disabled="">CONTINUE </button> to be like this instead: <button _ngcontent-c19="" class="blue- ...

What is the best method to retrieve the country name from a world map using D3.js?

I'm trying to figure out how to retrieve the country name from a click event on the D3 world map. Despite inspecting the DOM, I can't quite understand how the country's name, code, or population is associated with the map. The template for ...

What is the best way to apply the TableRow style in material-ui / mui to make it similar to TableHead?

Trying to implement TableHead styling on TableRow but encountering a warning: validateDOMNesting(...) cannot be a child of. How can this be fixed without triggering a warning message? CollapisbleTableRow.js import React, { Fragment, useCallback } from &ap ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...