Exploring how to successfully test the parsing of a string using JSON.parse in Jest

Currently, I am in the process of creating unit tests for an API.

In a scenario where I implement the following code:

const apiResponse:object = JSON.parse(body)
expect(apiResponse).toHaveProperty('error')

If the API does not return JSON data, an error message is displayed:

SyntaxError: Unexpected token p in JSON at position 0 at JSON.parse ()

Instead of encountering errors during testing, I would prefer my test to fail if the JSON parsing fails.

I am looking for a jest test that can verify:
Can the string received be parsed as valid JSON?

Answer №1

I managed to tackle this issue by incorporating a helpful function I stumbled upon here

const validateJSON = (str:string) => {
    try {
        const json = JSON.parse(str);
        if (Object.prototype.toString.call(json).slice(8,-1) !== 'Object') {
        return false
        }
    } catch (e) {
        return false
    }
    return true
}

Subsequently, I could execute the following:

expect(validateJSON(body)).toBe(true)

Answer №2

To ensure that JSON parsing does not throw an error, you can utilize Jest's .not.toThrow() method.

Check out this custom example demonstrating how to assert that an object can be parsed into valid JSON:

it("Verifies metadata object can be converted to valid JSON", () => {
    const meta = articleMetaData(article);

    const parseJson = () => {
        const json = JSON.stringify(meta);
        JSON.parse(json);
    };

    expect(parseJson).not.toThrow();
});

If, for instance, the object exhibited a circular structure like so:

var obj = {
  a: "foo",
  b: obj
}

The test would result in failure:

The function was expected not to generate an error.
Instead, it produced:
    TypeError: Converting circular structure to JSON

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

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

Error message: Attempting to access the property '_layerAdd' of an undefined object in the context of vue and leaflet integration

Encountering an issue while attempting to include a feature group on my map: TypeError: Cannot read property '_layerAdd' of undefined The section of code causing the error: <l-map id="mapid" :zoom="zoom" :center="center" /> var ...

Generate several JSON files from a CSV file by categorizing items

A CSV file has been provided: year,product,price 2021,P01,50 2022,P03,60 2021,P02,30 The goal is to generate a JSON object for each year containing the list of products like so : { "year": "2021", "products": { &quo ...

What are the steps to installing a .deb file offline using Docker?

I am planning to install a .deb file on my Docker container. In my Dockerfile, I execute the following command: RUN apt-get install -y ./fonts/ttf-mscorefonts-installer_3.6_all.deb ROOT Folder |->Dockerfile |->fonts |-> ttf ...

The cache does not contain '.chunk-`X`' as requested in Next.js error

Hello everyone, I've encountered a recent issue with my code that previously worked fine. I was using getStaticProps with a cache time of 5 days, but now I'm facing an error related to the title. Here is a more detailed look at the error: error ...

Only make an AJAX request for suggestions with jQuery Autocomplete if the item does not match any data from the previous request

I am currently working with jQuery Autocomplete functionality. The issue I am facing is that it triggers an AJAX request every time a key is pressed, which is not desirable. Ideally, if the data from a previous AJAX request already matches the search query ...

Error: The value of 'PlacesService' property is not defined and cannot be read

I am working towards gathering a selection of locations that meet specific criteria by making a "routeRequest" and storing them. To achieve this, I aim to utilize Google Places to search for locations around the central point of my map. let map = new goog ...

Fixing JQuery Promise Failure in React.JS ComponentDidMount

When utilizing the ComponentDidMount life cycle method in my components, I encountered an issue with an AJAX request. Despite successfully retrieving data, the promise chain kept deferring to the fail property. This puzzling behavior persisted even when I ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

The animation function in A-frame causes entities to vanish when used with D3.js

Working with the animation property in D3.js has been a bit of a challenge for me. When I include the a-animation directly in the HTML section, everything works as expected. <a-box id="box" position="0 1 0" rotation="0 0 0" scale="1 1 1" color="#4CC3D9 ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Converting a C# class into JSON format and sending it back

string searchQuery = context.Request.QueryString["tag"]; System.Web.Script.Serialization.JavaScriptSerializer customSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); context.Response.ContentType = "application/json"; ...

After the page has finished loading, I aim to have the modal window pop up after 10 seconds. Thank you to all!

$(document).ready(function() { var id = "#dialog"; //Calculate screen dimensions var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Adjust mask to cover entire screen $('#mask').css({'wid ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. https://i.sstatic.net/6oseq.png Although I thought I had a ...

Sending an array with a specific identifier through JQuery ajax

I'm facing an issue where I am sending an array of values via jQuery AJAX to my servlet. However, the servlet is only picking up the first value in the array, even though there are more elements present. $.ajax({ type: "POST", url: "mySer ...

Tips for simplifying a JavaScript function

Hello everyone, I just joined StackOverflow and I could really use some assistance with a JavaScript and jQuery issue that I'm facing. Can someone suggest a more efficient way to write the code below?: jQuery(document).ready(function () { $("#ar ...

Is it possible to update a Rails element using an AJAX request?

I've delved into a plethora of information regarding Rails, AJAX, and 5.1 Unobtrusive Javascript. It provides insight on how to handle AJAX calls in Rails with a .js file, for example. However, my goal isn't to serve up an entire .js file; rathe ...