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

Build a brand new root component in Vue JS

I am facing a challenge with destroying and re-creating the root application component. Below is my template structure: <div id="app"> {{ num }} </div> Here is the code I have implemented: if (app) { app.$destroy(); } else { ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

Success function in Classic ASP with Ajax Form isn't functioning properly, but the complete function is working fine

When using Ajax and JS/Jquery, I am attempting to send a basic Contact form to a Classic ASP (aspemail) without reloading the page. <form id="form-submit" action="ASPEmail.asp" method="post"> Name<br> <input id="name" type="text"&g ...

Utilize React JS to parse and display a sophisticated JSON structure in a dropdown menu

Looking at the backend data structure provided, we have information on various courses in different departments. { "courseDetails" : [{"departmentId" : 105654, "courses" : [{"stream" : "science","courseIds" : ["104","105 ...

Extracting data from websites using Python's Selenium module, focusing on dynamic links generated through Javascript

Currently, I am in the process of developing a webcrawler using Selenium and Python. However, I have encountered an issue that needs to be addressed. The crawler functions by identifying all links with ListlinkerHref = self.browser.find_elements_by_xpath( ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

What steps can I take to successfully run Node.js within Eclipse when the JavaScript runtime is not showing up in the preferences?

I have been encountering some difficulties with integrating Node.js into my Eclipse IDE for enterprise Java developers. I am using Eclipse Ide 2021-06 and have installed Node.js 16.3 along with npm. According to the Eclipse news, Eclipse Neon and later ve ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Avoiding default action on keyboard tab event resets cursor position while typing consecutively

Issue with cursor position resetting to start when tab is the last key pressed I am working on a chrome extension for Gmail using React and need to customize the behavior of the tab key. I have found that using preventDefault and stopImmediatePropagation ...

Issue with retrieving JSON data through HTTP Get request on Internet Explorer, while it works fine on

Trying to upgrade a basic weather plugin by integrating geolocation services that identify a user's location based on their IP address. Smooth sailing on Chrome and Firefox, but IE seems to be causing some trouble. Any idea what might be the issue wit ...

Attaching a modal to an entity

I am currently working on binding a Knockout (KO) viewmodel to a Bootstrap modal, but it seems like I am overlooking a step to direct KO to fill in the input fields. Below is the current setup: The template for the modal: <script type="text/html" id= ...

Using " " to split a name into two lines is not being recognized

My issue involves the display of tab names in two lines within multiple tabs. You can view the demonstration here. I attempted to use the \n character while setting the tab name but it was not recognized. Any suggestions on how to achieve this? Here ...

What steps should I take to enable this SimpleModal to load automatically?

Is there a way to have the SimpleModal script load when the page loads instead of having to click a button? Thank you for your help! < div id='basic-modal' > <a href='#' class='basic'>Demo</a> </div> ...

Unit testing with Jest involves creating mock implementations of IF conditions within functions to ensure complete code coverage

Currently, I am working with an API script stored in a file. const ApiCall = { fetchData: async (url) => { const result = await fetch(url); if (!result.ok) { const body = await result.text(); // uncovered line throw new Error(`Err ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

Enforcing Single Menu Accessibility in React: Only One Menu Open at a Time

Just starting out with React and JavaScript, so please bear with me for any formatting issues or lack of knowledge on best practices. I'm using Tailwind UI for my website, which includes navigation menus that require JavaScript to open and close. I h ...

Issue with CORS Policy specifically in this scenario despite functioning properly for other assets

My API is built with Laravel and for the front-end, I am using Vue.js with Nuxt.js. I have successfully installed the CORS policy package, which is working well with all my other resources. However, I encountered an error for one of my features: ...

Is there a way to determine if a field has been interacted with and meets validation criteria using VeeValidate?

I'm attempting to retrieve the validation flags from a computed property: computed: { isFormValid() { let isValid = this.$validator.fields.some(field => { console.log(field.flags); return field.flags.touched || field.flags.invali ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

Once I've located the correct document, how can I search for the object with the specific date and then modify it in mongoose?

I am currently working on creating a heatmap using react-d3-heatmap, and the data structure required for this is [{date: Date, count: Number}]. Below is the schema I have set up for this model. const HeatMapSchema = new mongoose.Schema({ user: {type: ...