What is the best way to simulate an external class using jest?

My Vue page code looks like this:

<template>
   // Button that triggers the submit method
</template>

<script>
import { moveTo } from '@/lib/utils';

export default {
  components: {
  },
  data() {
  },
  methods: {
    async submit() {
      moveTo(this, COMPLETE_ACTION.path, null);
    },
  },
};
</script>

Now, I'm facing an issue with my test file for this page. I am trying to use Jest to check and assert that the moveTo method is called with the correct parameters. However, I keep getting an error showing expected undefined but received an object. Here are some key points from the test file:

  import * as dependency from '@/lib/utils';
  dependency.moveTo = jest.fn();
  // Triggering the button call which in turn calls the submit method on the page
  expect(dependency.moveTo).toHaveBeenCalledWith(this, COMPLETE_ACTION.path, null);

I am confused about the context of this in this scenario and unsure about what I should pass in its place. It's worth noting that I am using the mount helper from Vue Test Utils.

Answer №1

After encountering a problem, I identified the issue to be related to the this parameter in the test code. It appeared that this was not defined as expected, causing a mismatch with a VueComponent.

To resolve this issue, I utilized my wrapper object and accessed the VueComponent by making use of the vm property as specified in the documentation: https://vue-test-utils.vuejs.org/api/wrapper/#properties

Subsequently, I made an adjustment to the code by including wrapper.vm in the following line:

  expect(dependency.moveTo).toHaveBeenCalledWith(wrapper.vm, COMPLETE_ACTION.path, null);

Answer №2

To properly test your module, you should mock the module itself in this situation. It seems like you're trying to assert on a spy function that is not being called.

To add a module mock, you can create a "mocks/ subdirectory right next to the module". If it's a node module you're mocking, such as lodash, place the mock in the mocks directory next to node_modules.

In this case (there are alternative methods), you'll need to create a __mocks__ folder alongside the node_modules directory and then create a file at __mocks__/lib/utils/index.js where you export the mocked function:

export const moveTo = jest.fn()

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 is the best way to utilize the .done() callback in order to execute a function when new data is loaded upon request?

I have a web page that pulls data from a JSON feed, and there's also a button to load more content from the feed when clicked. I want to add additional elements inside the page for each item in the feed. I've managed to create a function that doe ...

Transferring API information into a nested array and displaying the outcome

Currently, I am utilizing an API to fetch an array of users from which I sort them and collect those with a personalTrainerId matching my userId into an array. The ultimate goal is to render these users as cards on the interface. The desired format for th ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

The vue-cli-plugin-cordova does not work on the iOS simulator by default

The following steps are outlined: vue create my-app vue add cordova npm run cordova-prepare npm run cordova-serve-browser These steps work fine npm run cordova-serve-ios Some sources suggest changing the above to: new Vue({ el:'#app', ...

Incorporating VueJS into a complex WebForms project with multiple pages

I'm currently working on a webforms project and I would like to incorporate VueJS into it. However, I am facing challenges when trying to set up the root element. If I enclose my content within a <div id="app"></div> element and specify t ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

Timer Does Not Appear to be Counting Down

I recently added a countdown clock to my website, but I'm having an issue with it not updating in real-time unless the page is refreshed. I'm not very familiar with javascript, so I found some code online and made some modifications myself to sui ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Is Vue.js rendering jQuery obsolete?

Is it true that utilizing vue js will render the jQuery library unnecessary for experienced developers? I would appreciate any insight on this matter. ...

Error: Trying to set a value to an undefined object in the bind() method

I am currently working on implementing a listener for my video player in order to update the input range on some custom controls. However, I have encountered an issue with an error message that states Uncaught ReferenceError: Invalid left-hand side in as ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

The React task list updates the todo items on change, rather than on submission

As a newcomer to React, I have embarked on the classic journey of building a todo app to learn the ropes. Everything seems to be functioning smoothly except for one minor hiccup: When I input a new todo and hit "submit", it does get added to my array but d ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

Is there a way to handle the ajax request only when necessary, instead of processing it every few seconds?

Currently, I am working on an AJAX chat system using PHP, MySQL, JavaScript, and AJAX. I have a piece of code that retrieves all chat messages within a div using AJAX, with the function running every 2 seconds. My issue lies in the fact that the div autom ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...