简体   繁体   中英

Checking the value in the array javascript

I am doing some API testing.

I am trying to check the name from the API response.

The API response is presenting data in an array.

I am checking if the name activeadmin exists however I am getting back an error The Repository activeadmin exists | AssertionError: expected 'pineapple' to deeply equal 'activeadmin'

I dont understand why its checking the second name value in the array rather then the first one?

Here is my code

let jsonData = pm.response.json()

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

I have tried using item[0].name but this comes back with error name is undefined

Below is 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
 } ]

The code works correct. It's iterating through every element of the response. You are using _.each where I guess it takes the 0, the 1, etc.

So it crashes when it goes into the second element which clearly doesn't have your specified name.

You should access your jsonData[0] element's name.

You can implement the test functionality in a different function an apply it on jsonData[0].

If this doesn't work for you, provide us with information about the test function and the pm object.

Everything is working as expected. Problem is that whenever you call pm.expect it will check if the name is 'activeadmin' . Since you have an array of values it will fail the test soon as it fails the first time. To fix this I would suggest the following code:

let jsonData = pm.response.json()

pm.test('The Repository activeadmin exists', () => {
    let activeAdminExists = false
    _.each(jsonData, (item) => {
        if(item.name == 'activeadmin'){
             activeAdminExists = true
        }
    });
    pm.expect(activeAdminExists ).to.eql(true)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM