【发布时间】: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