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, executes an action, and navigates to a different location. How can I verify that isLoading is toggled correctly (true before the action is executed and false afterwards)?

Answer №1

Extract the rows containing this.isLoading into a separate function named setLoading() and verify if it has been invoked.

Answer №2

When using shallowMount/mount, the second parameter represents the mounting options that can be utilized to replace the component's data props during mounting. This allows for the implementation of a setter to simulate changes to the isLoading data prop, enabling verification of property modifications within the method being tested:

it('sets isLoading', () => {
  const isLoadingSetter = jest.fn()

  const wrapper = shallowMount(MyComponent, {
    data() {
      return {
        // This setter is triggered when `this.isLoading = value` is called in the component.
        set isLoading(value) {
          isLoadingSetter(value)
        }
      }
    }
  })


  //...
})

Subsequently, you can employ toHaveBeenCalledTimes() in conjunction with isLoadingSetter.mock.calls[] to inspect the arguments passed to the mocked setter in each invocation. To evaluate the consequences of an async function, await the method execution before asserting any outcomes:

it('sets isLoading', async () => {
  //...

  await wrapper.vm.method()

  expect(isLoadingSetter).toHaveBeenCalledTimes(2)
  expect(isLoadingSetter.mock.calls.[0][0]).toBe(true)
  expect(isLoadingSetter.mock.calls.[1][0]).toBe(false)
})

If validating the invocation of GET_OFFERS() is also required, utilize jest.spyOn() on the component's method prior to mounting:

it('gets offers', async () => {
  const getOfferSpy = jest.spyOn(MyComponent.methods, 'GET_OFFERS')
  const wrapper = shallowMount(MyComponent, /*...*/)
  await wrapper.vm.method()
  expect(getOfferSpy).toHaveBeenCalledTimes(1)
})

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

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Add the value to the array in MongoDb only if it does not already exist in

Looking to make updates to a nested array within a document only if the item is not already included in the array: await userCollection.findOneAndUpdate( { _id: ObjectId('616acc597ebda90ca6ffee21') }, { 'devices': { ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

Guide on accessing the final value of a text file using JavaScript

My server side script outputs results in a txt file, where the values stored look like this: 1 2 5 7 10 In order to create a real-time progress bar, I need to fetch the last value from the file using an ajax request while updating the txt file with the l ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

Loading Textures in Three.js Using async / await is the Way to Go

Recently, I took a Drawing class and learned about creating objects: export class Drawing { constructor(texture) { const material = new MeshBasicMaterial({ color: 0xffffff, map: texture }); this.m ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

Is there a way to trigger jQuery animations even when the browser window is not in focus?

Hi there, I am currently working on developing an ajax-based multiplayer game that connects to a server for updates. The game has various game states and requires the GUI to be animated accordingly. However, I have encountered a problem where jquery anima ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...

Utilize Typescript/Javascript to utilize the Gmail API for sending emails via email

I am trying to send emails from my application using my Gmail account with Ionic. I have followed tutorials from SitePoint and Google Developers. Here is how I'm initializing the client: client_id: gapiKeys.client_id, discoveryDocs: ["https://www.goo ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

Are the elements in the second array the result of squaring each element in the first array? (CODEWARS)

I am currently working on a 6kyu challenge on codewars and I've encountered a frustrating issue that I can't seem to figure out. The task at hand involves comparing two arrays, a and b, to determine if they have the same elements with the same mu ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

React does not auto-populate form data

I am working on a simple project using Next.js with a basic form. However, when I try to submit the form and log the form data in the console, it shows up as an empty object. I'm puzzled by this issue. Here is my code: import styles from &apos ...

jQuery shorthand conditional statements

I currently have a jQuery function that is triggered by two separate buttons. $("#btnSearch, #btnDirectorSearch").click(function () { The construction of the HTML output within this function relies on which button was clicked. To accomplish this, I am ut ...