ROMAN SKRIPNIKOV
ROMAN SKRIPNIKOV

Reputation: 1

TypeError: Cannot read property 'sessions' of undefined

I am writing tests and I do not know js well, but I need to find the answer quickly. In the courses, I have not reached this point yet, or maybe I just don’t understand. Please help me figure out what I'm doing wrong.

I have two questions:

if you do not delete this line, an error appears: TypeError: Cannot read property 'sessions' of undefined

(props: { authId: string; deviceId: string })

This is the response.body I am trying to parse:

{
  "result": {
    "sessions": [
      {
        "type": "web",
        "authId": "jRXtO7oNiBR5Ldeq",
        "platform": "platform",
        "application": "application",
        "seenAt": 1592052380
      }
    ],
    "integrations": []
  },
  "success": true
}

My code:

import { agent } from 'supertest';
import { config } from '../../config';
import { getSsoId } from '../../helpers/getUserFromGenesis';

describe('First', () => {
    let id;
    let authId;

    beforeEach(async () => {
        id = await getId();
    });

    const userAuthorizations = (fn: (response: any) => void) =>
        agent(config.baseUrl)
            .get(`users/${id}/authorizations?client_id=test`)
            .auth(config.user, config.pass)
            .expect((response) => {
                fn(response);
            });

    const deleteUserAuthorizations = (props: { authId: string; deviceId: string }) =>
        agent(config.baseUrl)
            .delete(`users/authorizations`)
            .auth(config.user, config.pass)
            .send(props)
            .expect((response) => {
                expect(response.body.result.success).toEqual(true);
            });

    const getSession = () =>
        agent(config.tokenQaUrl)
            .post(`/token`)
            .auth(config.user, config.pass)
            .send({
                clientId: 'test',
                userId: id,
            })
            .expect((response) => {
                expect(response.body.sessionId).not.toEqual('');
                expect(response.body.sessionId).not.toEqual(null);
            })
            .then((response) => {
                authId = response.body.result.sessions[0].authId;
            });

    it('test', async () => {
        await getSession().then(() =>
            userAuthorizations((response) => {
                expect(response.body.result.sessions.length).toBeGreaterThan(0);
            }),
        );
    });
});

Upvotes: 0

Views: 8668

Answers (2)

user6269972
user6269972

Reputation: 319

I am a bit unclear on your question. There are some good answers up top.

In case you are trying to avoid a "property of undefined error" you can do something like this:

authId = response?.body?.result?.sessions[0]?.authId;

it prevents the error. Ideally you would type-check all of them.

Upvotes: 0

Aditya toke
Aditya toke

Reputation: 511

As discussed in the comment

  1. It seems like some time your response is getting the JSON data in the way which you are trying to access, but some time its not. Its better to add conditions before trying to access data where the JSON is not of fixed structure.

  2. To make these property optional just add ? it will make the properties option props: { authId?: string; deviceId?: string }

Upvotes: 0

Related Questions