【问题标题】:TypeError: Cannot read property 'sessions' of undefinedTypeError:无法读取未定义的属性“会话”
【发布时间】:2020-10-03 04:32:46
【问题描述】:

我在写测试,对js不太了解,但需要快速找到答案。在课程中,我还没有达到这一点,或者我只是不明白。请帮我弄清楚我做错了什么。

我有两个问题:

  • 一删除该行,测试就开始工作:

    .then((response) => {
       authId = response.body.result.sessions[0].authId;
    });
    

如果不删除此行,则会出现错误: TypeError: Cannot read property 'sessions' of undefined

  • 如何写,使字段可选,即可以通过,也可以不通过

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

这是我要解析的 response.body:

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

我的代码:

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);
            }),
        );
    });
});

【问题讨论】:

  • fields are optional 表示您必须将这些字段设为可选 props: { authId: string; deviceId: string }
  • 也就是说,在这种形式下它们是可选的吗?
  • 不,它们不是可选的,但如果你想让它们成为可选的,请尝试在它们前面添加?,例如props: { authId?: string; deviceId?: string }
  • 关于您的第一个问题,在尝试访问会话之前首先检查 request.body 中存在的内容
  • 是的,很抱歉,没有添加。这是我要解析的 response.body:{ "result": { "sessions": [ { "type": "web", "authId": "jRXtO7oNiBR5Ldeq_token_service", "platform": "platform", "application": "application", "seenAt": 1592052380 } ], "integrations": [] }, "success": true }

标签: javascript typescript jestjs testng supertest


【解决方案1】:

如评论中所述

  1. 您的响应似乎有时会以您尝试访问的方式获取 JSON 数据,但有时并非如此。最好在尝试访问 JSON 结构不固定的数据之前添加条件。

  2. 要使这些属性可选,只需添加? 它将使属性选项 props: { authId?: string; deviceId?: string }

【讨论】:

    【解决方案2】:

    我对你的问题有点不清楚。上面有一些很好的答案。

    如果您试图避免“未定义错误的属性”,您可以执行以下操作:

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

    它可以防止错误。理想情况下,您将对所有这些进行类型检查。

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2021-11-13
      • 2021-07-02
      • 2021-10-29
      • 1970-01-01
      • 2016-11-30
      • 2021-06-25
      • 2021-10-26
      相关资源
      最近更新 更多