Experimenting with isomorphic-fetch in a ReactJs environment

I have a function that I want to test using mocha and chai's expect method. The function uses "fetch" and "dispatch" as functions. "fetch" is responsible for making AJAX calls to the server.

Here is the function:

function fetchMetadata() {
   return (dispatch) => {
       fetch('/json/metadata').then(
           (result) => {
               if (result.status === 200) {
                   return result.json();
               }
               throw "request failed";
           }
       ).then(
           (jsonResult) => {
               dispatch(jsonResult);
           }
       );
   }
}

I'm having trouble testing it because the error is being swallowed by the promise. To address this, I am using "fetchMock," a function that mocks the "fetch" function.

Here is my test code:

describe('Should work', () => {

    before(() => {
        fetchMock.mock('^/json/metadata', {body1:"testing"})
    });

    it.only('should fetch metadata when fetchMetadata is called ', function(){
        let returnedFetchMetadataFn = fetchMetadata();
        let mockDispatch = (argument) => {
            expect(argument).toBe('SET_METADATA1');
        };

        returnedFetchMetadataFn(mockDispatch);

    });
});

I can't seem to get the test to fail. What am I missing or doing wrong?

Answer №1

Explore the capabilities of the promise-sync library. This library serves as a synchronous simulation of promises, enabling you to specify the specific assert errors to overlook within the success/error/finally callbacks.

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 invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Javascript files saved as post meta are failing to load on Wordpress pages

I am facing an issue with my site's load time and storing JavaScript for each page. All my attempts to load JavaScript stored as metadata have been unsuccessful. Whenever I try to load the JavaScript, it displays <script> </script> with a ...

A guide on creating unit tests for a function that utilizes dbus to extract data from Spotify

Here is a function that retrieves information from Spotify using dbus: def get_info_linux(): import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

The issue with HTML where the header and footer elements are continuously repeating when

I'm struggling with the title header and footer repeating on every printed page. I just want to show the title at the top of the page and display the footer at the end of the print page. Can anyone provide a solution or suggestion? You can view my fid ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...

What is the solution to resolving the error in Travis CI stating "Installation failed - version 13.7.0. It appears that the remote repository may be

Struggling to configure a basic JS project with Travis CI, but encountering consistent errors. The job log indicates an issue with installing the specified Node version during NVM installation. I have experimented with altering the Node version and confi ...

Explore the wonders of generating number permutations using JavaScript recursion!

After providing the input of 85 to this function, I noticed that it only returns 85. I am confused as to why it is not recursively calling itself again with 5 as the first number. console.log(PermutationStep(85)); function PermutationStep(num) { var ...

The Forge Viewer's getState() function is providing inaccurate values for individual items

In our Angular application, we have integrated the latest version of Forge Viewer and are storing the current state of the viewer in our database for future restoration. After thorough testing, we discovered that isolated nodes are not being saved correct ...

How come my program gets stuck in a never-ending loop whenever I try to access the API?

I am facing an issue while trying to call my API to retrieve the name of a TP. In the view, all I see is [object promise], and in the browser console, it seems like there is an infinite loop happening. HTML: <table [dtOptions]="dtOptions" cla ...

How can I create a dynamic height for a scrollable div?

How can I build a section with a defined height that contains a sticky header (with a dynamic height) and a scrollable body? I want the body to be scrollable, but due to the header's changing height, I'm unable to set an exact height. What should ...

Configuring settings for gulp-jshint

I'm currently utilizing gulp to compile my JavaScript code. My intention is to run jshint on the files before concatenating them, but I'm encountering difficulties in configuring the options properly. Am I handling this process correctly? var re ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

Mirage blocking Ember.js ajax POST request from going through

Currently, I am in the process of writing tests for a component within my Ember application. This particular component is responsible for executing an ajax POST request to communicate with my servers API and retrieve a file location string as a response. ...

Tips for saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...

Receiving 'Unexpected end of input' error when using a string as a JavaScript function argument

I am trying to implement an ajax request function in my project. This is the code snippet I have: function Reject(id, scomment) { jQuery.ajax({ type: "POST", url: "reject.php", data: {id: id, Scomment: scom ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Printing to the console: the array is empty and contains just one element simultaneously

I've encountered an issue regarding the console.log function that seems related to a specific case I found... JavaScript array length problem Upon checking my console, I noticed this output: https://i.stack.imgur.com/AbCdE.png The code snippet in ...