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

Enabling HTTPS as the default for axios HTTP requests

My challenge lies in setting up an ajax request with axios that specifically needs to be made over https. axios.get('/relativeurl') .then((response) => { console.log(response); }) .catch((error) => { console.log ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Generating an interactive table using JSON data in ReactJS

I am a beginner in both React and UI development, and I would like to know how I can create a visually appealing table using the JSON data received from an AJAX call to the server. Any guidance or information on this topic would be greatly appreciated. v ...

I have developed a website that can calculate the factorial of any given number. The next step is to design a function that will display the step-by-step mathematical process

Could use a hand with this one. The function below is empty and I'm a bit stuck on what to do next. Right now, the webpage displays the factorized number, but I want to show the mathematical equation before it, like so: User inputs: 3 Site outputs: " ...

Unlocking the Power of Select Options in Vue.js

I am currently learning how to use Vue.js. Below is an example of the Javascript code I have written: new Vue({ el: '#app', data: { classes: [] }, created: function () { var vm = this // Fetch API ...

Struggling to locate the element for clicking or sending keys in Selenium using Java?

Hi everyone, I'm a new member of this forum and I'm just starting out with coding for the first time. I have encountered an issue with a specific part of my code: md-input-container class="md-default-theme md-input-invalid">> label for="i ...

AngularJS HTTP POST request encountering issue with success function not functioning as expected

I am currently working on implementing a basic HTTP post request to insert data into my database. The following pages are involved: register.php contains the registration form. maincons.js houses the application controllers. sqlregister.php include ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Animating the Three.js Globe camera when a button is clicked

Struggling to create smooth camera movement between two points, trying to implement the function below. Currently working with the Globe from Chrome Experiments. function changeCountry(lat, lng) { var phi = (90 - lat) * Math.PI / 180; var theta = ...

Incorporating an external Angular.js library into a Vue.js Single File Component

I am working with a Single File Component in Vue.js that includes the following code. The plasmid tag should be rendered by the angularplasmid.complete.min.js file, but it doesn't seem to be working. I'm wondering if this is the correct way to i ...

Vue 3 App experiencing issues displaying Bootstrap 5 offcanvas component

I am currently working on integrating the new offcanvas feature of Bootstrap 5 into my Vue app. I have written the code, and after building the app, I am attempting to test it. However, I am facing an issue where the offcanvas menu is not visible. To kee ...

What is the process for incorporating an animated gif into a scene?

I'm trying to incorporate an animated gif in three.js. What's the best way to do it? var materialTextured = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('images/pin.gif'), transparent: true, ...

In certain cases, the functionality of updating and saving data with Mongoose may be intermittently successful within

As a C++ developer who has recently inherited a node.js project, I am struggling with a frustrating bug that I can't seem to fix due to my limited mongoose skills. The function below is supposed to retrieve data from a form, save it, and change an ad ...

Is there a way to conceal the parameters in the PHP GET method?

How to convert PHP GET method URL to a cleaner format? example.com/example.php?name=45 to example.com/example.php/45 Is it possible to achieve this using the .htaccess file? ...

A guide to adding a picture to AWS S3 with the help of GraphQL

When trying to upload a base64 string via GraphQL, I encountered an issue. It seems that if the string exceeds 50,000 characters, GraphQL fails to reach the resolve function without giving any error messages. However, when the string is less than 50,000 ...

Using Traefik for HTTPS redirection with Docker Compose, the Vue+Nginx application is encountering a 404

Hello everyone, I am a newbie developer and excited to share that I am deploying my first full stack project. I'm currently working on running a vuejs+nginx client app in a docker-compose setup which includes mysql, a nodejs backend, and traefik for ...

Rendering images from Laravel's storage folder in a React component

When uploading an image from a React frontend to a Laravel backend, I encountered an issue where the uploaded image path was saved in the database but the image wouldn't display. React code ` useEffect(() => { axiosClient .g ...

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

The issue of the "port" attribute not working for remotePatterns in the Image component has been identified in Next.js 13's next.config.js

I've encountered an issue with the code snippet below. I'm attempting to utilize remotePatterns in my next.config.js file to enable external images. Strangely, when I set the port to an empty string "", it functions correctly. However, specifying ...