Examining the contents of an array in JavaScript

I am currently conducting API testing.

My objective is to verify the presence of a specific name within the API response.

The data from the API response is structured in an array format.

Despite my intention to check for the existence of the name "activeadmin," I encountered an error that reads: The Repository activeadmin exists | AssertionError: expected 'pineapple' to deeply equal 'activeadmin'

I am puzzled as to why the comparison is being made with the second name value in the array instead of the first one.

Below, you can find the code snippet I have been working on:

let jsonData = pm.response.json()

pm.test('The Repository activeadmin exists', () => {
    _.each(jsonData, (item) => {
        pm.expect(item.name).to.eql('activeadmin')
    })
})

I attempted to use item[0].name, but this resulted in an error stating that the name property is undefined.

Here is an extract of the API Response:

   [
{
"id": 2847287348,
"node_id": "sdhjaskdhkjasdhjashd",
"name": "activeadmin",
"full_name": "apple/activeadmin",
"private": false
   },
 {
"id": 2847287348,
"node_id": "sdhjaskdhkjasdhjashd",
"name": "pineapple",
"full_name": "apple/activeadmin",
"private": false
 },
 {
"id": 2847287348,
"node_id": "sdhjaskdhkjasdhjashd",
"name": "orange",
"full_name": "apple/activeadmin",
"private": false
 } ]

Answer №1

The script functions properly by iterating through each element of the received data. Instead of using _.each, it is likely going through the elements one by one starting at index 0. However, this leads to a crash when it reaches the second element, which may not contain the expected name. To resolve this, access the name property of the jsonData[0] element specifically.

Consider creating a separate function for testing purposes and apply it to the jsonData[0] object. If you continue to experience issues, please provide details about the test function and the pm object being used.

Answer №2

Everything is going according to plan. However, there seems to be a small issue when using the pm.expect function. It currently checks if the name is equal to 'activeadmin'. This causes a problem as it stops the test as soon as it encounters a value that doesn't match. To resolve this issue, you can use the following code snippet:

let jsonData = pm.response.json()

pm.test('Check if activeadmin exists in the Repository', () => {
    let activeAdminExists = false
    _.each(jsonData, (item) => {
        if(item.name == 'activeadmin'){
             activeAdminExists = true
        }
    });
    pm.expect(activeAdminExists ).to.eql(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

Error: The variable "user" has not been declared in server.js when using passportjs

As a novice with limited experience and a tendency to borrow code snippets from various sources, I'm struggling to identify the root cause of the Reference Error: User is not defined. This particular error crops up when I try to input or submit a new ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

What is the clarification regarding accessing JSON from various domains?

(I am aware of the fact that ajax calls must originate from the same domain, and have already gone through relevant responses) However, I am having trouble grasping something: We often see platforms like Facebook use the for(;;) || while(1) pattern in ...

EJS functionality is operational, however, the HTML content is not displaying

I'm currently developing a timer using Express.js and EJS. My goal is to update the HTML dynamically, but I seem to be encountering an issue where nothing gets displayed. Strangely enough, I can see the output in my CLI with console.log. <div id ...

Detecting a targeted POST event in JavaScript without any libraries

In a situation I'm facing, an AngularJS website is not loading jQuery (except for jQLite). My goal is to monitor events with particular parameters. Unfortunately, I'm unable to make any changes to the source code. However, by examining the event ...

How can we prevent the modal from extending beyond the boundaries of the phone screen when zoomed in

I am currently developing a web application that features a large content page, specifically a map which should display detailed information upon zooming in similar to Google Maps. The interactive elements on my map are clickable, triggering a modal popup ...

Unable to `.catch()` an error while utilizing Jquery.ajax().then()

My current project involves making calls to various APIs using JQuery and caching the response from each API. This cached data is then used multiple times on the page to create different dashboard widgets. The issue I'm facing is that if an API retur ...

How come the state update result is triggering two different responses?

I recently developed a basic TicTacToe game using react-hooks. At times, I notice that the result is displayed before the state update on the screen. Other times, the result shows up after the update is visible on the screen. I'm puzzled by this ...

Is it possible to utilize the `.apply()` function on the emit method within EventEmitter?

Attempting to accomplish the following task... EventEmitter = require('events').EventEmitter events = new EventEmitter() events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3']) However, it is ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...

Choose options with identical titles

If you click on the button to add more selects with the same name, I want to replace them so that you can access them in a PHP array. document.querySelector('#add').onclick = function () { var thespan = document.createElement('span&apos ...

Only one of the two scripts is functioning as intended

I'm facing an issue with two different scripts - the first one doesn't seem to work while the second one does. Oddly enough, when I remove the second script, the first one starts working. Can you help me find a solution? <script> // Ta ...

Managing Asynchronous Callbacks in JavaScript using Node.js

I am a beginner in the world of Javascript and I recently encountered a challenge with async callbacks using Node.js. My first step was setting up the Facebook webhook and sending a Webhook POST request Below is the code snippet : routes.js **Setting up ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

What is the best way to hide or eliminate spinners/arrows in react-select?

I am currently utilizing react-select for my project, but I'm encountering an issue with removing the spinners/arrows from the dropdown menu. So far, I have successfully removed the default separator "|" and Dropdown Indicator using the following cod ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

Error connecting Node.js, express, and socket.io application

My app is a simple one that utilizes the socket.io module for node.js. Everything runs smoothly when I start my server with the command node express_server.js. However, when I try to open my page at http://localhost:8080 in the browser, Node.js throws an e ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://localhost:1883') topic = 'testTopic' client.on('connect', ()=> { client.subscribe(topic) }) client.on(&a ...

What is the reason that asynchronous function calls to setState are not grouped together?

While I grasp the fact that setState calls are batched within react event handlers for performance reasons, what confuses me is why they are not batched for setState calls in asynchronous callbacks. For example, consider the code snippet below being used ...