{ it("user i-6ren">
gpt4 book ai didi

javascript - 如何在nodejs中使用chai期待http错误和响应

转载 作者:行者123 更新时间:2023-11-30 14:41:43 24 4
gpt4 key购买 nike

您好,我正在编写我的功能的单元测试用例。如果请求成功,此函数返回 json 响应,否则返回错误。

describe("Operations", async () => {

it("user info", async () => {
let accessToken = 'dfsf;
const result = await authConnectors.getUser(accessToken);


});

});

如何在 nodejs 中使用 chai 断言 http 错误和响应?

{ Error: Unauthorized
at Request.callback (/vagrant/node_modules/superagent/lib/node/index.js:699:13)
at IncomingMessage.parser (/vagrant/node_modules/superagent/lib/node/index.js:903:18)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
status: 401,
response:
Response {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
res:
IncomingMessage {
_readableState: [Object],
readable: false,
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
socket: [Object],
connection: [Object],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Object],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 401,
statusMessage: 'Unauthorized',
client: [Object],
_consuming: true,
_dumped: false,
req: [Object],
text: '',
read: [Function] },
request:
Request {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
_agent: false,
_formData: null,
method: 'GET',
url: 'https://id-dev',
_header: [Object],
header: [Object],
writable: true,
_redirects: 0,
_maxRedirects: 5,
cookies: '',
qs: {},
_query: [],
qsRaw: [],
_redirectList: [],
_streamRequest: false,
req: [Object],
protocol: 'https:',
host: 'id-dh',
_endCalled: true,
_callback: [Function],
res: [Object],
response: [Circular],
called: true },
req:
ClientRequest {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'GET oqcnM_4xWNbmv-WaoJ63UOjcZSHW-KrULLRUFzXrQKS6iuPWp6poHLjop1WsRtw5Y-KQCTZVI783awnn3_utEw6yqD6qpHHZwhxiPeM8mFZgN_zH4xX0ChbQ3ayao9Ms6ZHQT0X00N467HPfq5hVAW4D3a-3DURwnUvvVTIsYTShhZAsag2P26WDbKapPdgfVpjQKV-4GP--cLWbAZpEWJT3yS31YiY-VEcdfjdDU\r\nAccept: application/json\r\nConnection: close\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/userinfo',
_ended: true,
parser: null,
res: [Object] },
text: '',
body: {},
files: undefined,
buffered: true,
headers:
{ 'content-length': '0',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
'x-xss-protection': '1; mode=block',
'x-content-type-options': 'nosniff',
'content-security-policy': 'default-src \'self\';script-src \'self\' https://track.abc.net;style-src \'self\' \'unsafe-inline\' https://track.abc.net;img-src \'self\' https://track.abc.net;frame-src \'self\' https://track.abc.net;object-src \'none\';',
'www-authenticate': 'Bearer error="invalid_token"',
date: 'Wed, 28 Mar 2018 11:57:56 GMT',
connection: 'close' },
header:
{ 'content-length': '0',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
'x-xss-protection': '1; mode=block',
'x-content-type-options': 'nosniff',
'content-security-policy': 'default-src \'self\';script-src \'self\' https://track.abc.net;style-src \'self\' \'unsafe-inline\' https://track.abc.net;img-src \'self\' https://track.abc.net;frame-src \'self\' https://track.abc.net;object-src \'none\'',
'www-authenticate': 'Bearer error="invalid_token"',
date: 'Wed, 28 Mar 2018 11:57:56 GMT',
connection: 'close' },
statusCode: 401,
status: 401,
statusType: 4,
info: false,
ok: false,
redirect: false,
clientError: true,
serverError: false,
error:
{ Error: cannot GET /sts/connect/userinfo (401)
at Response.toError (/vagrant/node_modules/superagent/lib/node/response.js:94:15)
at ResponseBase._setStatusProperties (/vagrant/node_modules/superagent/lib/response-base.js:123:16)
at new Response (/vagrant/node_modules/superagent/lib/node/response.js:41:8)
at Request._emitResponse (/vagrant/node_modules/superagent/lib/node/index.js:739:20)
at IncomingMessage.parser (/vagrant/node_modules/superagent/lib/node/index.js:903:38)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
status: 401,
text: '',
method: 'GET',
path: '/sts' },
accepted: false,
noContent: false,
badRequest: false,
unauthorized: true,
notAcceptable: false,
forbidden: false,
notFound: false,
type: '',
links: {},
setEncoding: [Function: bound ],
redirects: [] } }

最佳答案

使用 expectshould 你可以测试如下:

describe('Testing https responses', () => {

it("user info", async (done) => {

.... request here...
.catch((err) => {
err.response.should.have.status(404);
err.response.body.should.have.property('error');
err.response.body.error.should.eql('User could not be found');

done()
});
})

it('testing using expect', (done) => {
request.get('http://localhost:8000', function (err, res, body) {
expect(res.statusCode).to.equal(400);
expect(res).to.have.property('body');
expect(res.body).to.equal('wrong header');
done();
});
});
})

These tests are asynchronous, so they need the promise to be solved at the end with done()

编辑 - 再次添加示例

.property(name[, val[, msg]])

Asserts that the target has a property with the given key name.

expect({a: 1}).to.have.property('a');

这里有三个有用的链接:

关于javascript - 如何在nodejs中使用chai期待http错误和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49534032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com