Jest check if a value is properly assigned in the .finally() block of a fetch request

During my Vue component testing, I encountered an issue with a method that utilizes a basic fetch operation to update a data value within the .finally() block. Despite verifying that my test successfully reaches the .finally() block, the data value fails to update.

The method in question looks like this:

updateProfile () {
  fetch(updateProfileEndPoint, {
      method: 'POST',
      body: {email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="403425333400342533346e232f2d">[email protected]</a>, id: 1234, name: 'bob},
    })
      .catch((error) => {
        this.errorField = true;
      })
      .finally(() => {
        this.profileUpdated = true;
      });

Within my Jest test environment, the setup includes:

const wrapper = mount(ProfileComponent, { store,
  data () {
    return {
      profileUpdated: false,
    };
   },
 });

 global.fetch = jest.fn(() =>
   Promise.resolve({
     profileUpdate: 'complete',
   })
 );

 wrapper.vm.updateProfile();
 expect(wrapper.vm.profileUpdated).toBe(true);

Despite confirming through console.log(this.profileUpdate) that the value does indeed update to true, the tests continue to receive false.

Answer №1

Your statement appears before the asynchronous fetch call actually finishes.

An alternative approach would be to have updateProfile() return the result of the fetch operation (which is a Promise), enabling the test to use await:

// MyComponent.vue
export default {
  methods: {
    updateProfile() {
      return fetch(...).catch(...).finally(...)
    }   👆
  }
}

// MyComponent.spec.js                           👇
it('updateProfile() updates profileUpdated flag', async () => {
  const wrapper = mount(...)
    👇
  await wrapper.vm.updateProfile()
  expect(wrapper.vm.profileUpdated).toBe(true)
})

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

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Integrating webpack with kafka-node for seamless communication between front

I am in the process of embedding a JavaScript code that I wrote into an HTML file. The script requires kafka-node to function properly, similar to the example provided on this link. To achieve this, I am using webpack to bundle everything together. I am fo ...

What is the most effective way to divide input elements into an array in Angular?

How can I bind an input value to an ng-model as an array? For example, if I enter one, two, three, I want the resulting model to be [ "one","two","three" ]. Currently, this is my approach: <input type="text" ng-model="string" ng-change="convertToArra ...

What is the best way to send a JavaScript variable to a GraphQL query?

I'm struggling with making my super simple GraphQl query dynamic based on input. The query is straightforward, but I need to replace the hardcoded string of "3111" with a value from a variable called myString. How can I achieve this in JavaS ...

Using CSS modules with React libraries

Currently working on a React website, I decided to eject my project in order to use css modules styles. After running npm run eject, I made additional configurations in the webpack.config.dev.js and webpack.config.prod.js files. However, I encountered an i ...

Divs that can be sorted are being shifted downwards within the swim lanes

JavaScript code snippet here... CSS code snippet here... HTML code snippet here... ...

Graphing functions with three.js

Is it possible to create a function grapher using the three.js API to plot a function in the form of z=f(x,y)? The program should: Generate input values between -1 and 1 in increments of .1, and use these values to plot x, y, and z vertices as part of a ...

Is there a JavaScript equivalent to the explode function in PHP with similar functionality

I'm facing an issue while attempting to split my string in JavaScript, here is the code I am using: var str = 'hello.json'; str.slice(0,4); //output hello str.slice(6,9); //output json The problem arises when trying to slice the second str ...

Modify choices in real-time using Vue.js multi-select feature

Hello, I've come across a modified wrapper for handling a multiple select in vue js using this. My goal is to change the value of "Bubble car" inside the vue component. Below is my code snippet. <select2-multiple :options="car_options" v-model="in ...

Setting the parent's height to match one of its children

I'm struggling to align the height of the pink '#images-wrap' with the main image. When there are too many small rollover images on the right, it causes the pink div to extend beyond the main image's height. If I could make them match i ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

I am interested in deleting an element from Firebase using JavaScript

I'm struggling to grasp the concept of deleting an item from my Firebase database. I have successfully created a function (saveEmployee) to add items, but removing them is where I hit a roadblock. HTML <tbody ng-repeat="employee in employees"> ...

"Upon loading an FBX file in Threejs, some model parts are not displayed

Hello, I am in need of assistance. I am currently working on importing FBX models into Threejs and here is the import code that I am using: let loader = new FBXLoader(); loader.load(model.obj_path, object => { let mix = new THREE.AnimationMixer(objec ...

Activate the click function of an asp.net linkbutton when the mouse enters by utilizing jQuery

I'm attempting to create a hover-triggered click event using jQuery. While this is a straightforward task, I've run into an issue where I can't seem to trigger the click event of an ASP.NET link button that refreshes the content of an updat ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Urgent concern: the require function is being utilized in a manner that prevents the static extraction of dependencies [mysterious]

After implementing the magic-sdk version 8.0.1 on my project, I encountered the following warning message: warn - ./node_modules/magic-sdk/dist/es/index.js Critical dependency: require function is used in a way in which dependencies cannot be statically e ...

What should be done when HTML5 anchor tag downloads fail due to a long base64 string in the src attribute?

batchDownloadImages() { const aTagDownload = [ { download:'foo', href:'HD image base64 string from canvas.toDataUrl()' }, { download:'bar', href:'HD image base64 string from canvas.to ...

Encountered an error when attempting to access property 'connect' of an undefined value

I encountered an issue with pg.connect not being defined in the Handler module. My goal is to set up a table using postgres in fastify. In my routes handling folder, I manage the routes and send API requests. The error occurs when I navigate to http://loc ...

jQuery: Implementing JavaScript on a page asynchronously through Ajax without triggering execution

When utilizing jQuery to execute an ajax request and insert code into my page, the added code includes both HTML and JavaScript. It seems that the JavaScript code is not being executed! What steps can I take to ensure that the newly added JavaScript sourc ...

Are reactive getters and setters for props automatically added for each child?

Consider a scenario where you are faced with an extensive list of tasks: [ { id: 1, name: Feed the ducks, priority: 'high' }, ... ] The system comprises of three interconnected elements - grandparent, parent, and child. ...