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

Breaking up a list into separate elements when creating a DataFrame with Pandas

I have received a JSON file that requires some operations and trimming. After processing, the output is as follows: print("User:", user) > User: {'id': 1, 'label': 'female', 'position': {'lat': 47.72485 ...

Using a ternary operator to render a span tag in ReactJS

I need to display a number in a span tag with larger font size in Spanish. Here is my React.js code using a ternary operator: <div> {togo !== 0 ? (<div className="text-center"><span className="display-4">{togo}</span>{togo > ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

Tips for eliminating duplicate values from an array of objects in JavaScript

I am working with an array of objects where my goal is to remove duplicate values from the values array. I would like the final result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', v ...

Input field with JQuery datepicker showing only months and years

I have encountered a question that closely resembles the one discussed here: year/month only datepicker inline The scenario I'm facing involves utilizing the input version instead of the div. In the case of using the div, the ui-datepicker-calendar ...

Unspecified data returned from PHP script via jQuery AJAX

Encountering an issue while trying to use AJAX to get a PHP response from a form. The JavaScript appears to be correct as it functions when the content of login_ajax.php is reduced to just: echo 'CORRECT' //or echo 'INCORRECT' Howev ...

Exploring the power of AngularJS with JavaScript and utilizing the $scope

After spending the entire day trying to solve this issue, it seems like I might be missing something simple. Here's the problem at hand: I have a well-structured Nodejs/AngularJS application that utilizes Jade for templating. The server performs certa ...

Effortlessly altering values within a dynamic key in Firebase's real-time database

I attempted to redefine the value as "pretend" using the code snippet below, but unfortunately it did not succeed. dataBase.ref().orderByChild('en_word').equalTo('pretend').set({ en_word: 'Pretend' }) ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

Working with MySQL fields in Laravel: Adding and fetching data

Currently, I am experimenting with a JSON field and facing some challenges. In my Customer model, I have added: protected $casts = [ 'billingConfig' => 'array' ]; To update a test field in my controller, I used: $custom ...

There is an issue with Nuxt 3 layers not functioning properly when trying to access a project page from a different

Is there a way to make a project function independently while still being accessible through layers and able to run smoothly? The current project structure is as follows: ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

Enhanced functionality in MUI TablePagination now allows users to easily select their desired page

I've implemented MUI TablePagination to enable pagination in my table. The code is performing well, offering most of the features I need: Users can choose between displaying 5, 10, or 20 entries per page using a dropdown. The number of pages displaye ...

When dealing with ReactJS, utilize the onChange event for handling updates to nested

I am currently learning ReactJS and struggling with a simple logic problem (I'm not very good at JS). I have a form that includes fields for name, email, and message. @ContactUsNew = React.createClass getInitialState: -> message: @props.mess ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format. [ { class: 'Reservation', sentence: 'make reservation' }, { class: 'Reservation', sentence: 'do reservation&a ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...