我正在尝试为发出get请求的功能编写基本的单元测试,并以降序/升序对用户业力点进行排序。我正在使用nock模拟http响应,但继续遇到错误,提示主机名未定义。
我仔细阅读了nock文档,以确认我正确地调用了主机名https://github.com/nock/nock#specifying-hostname,并跟随了youtube视频https://www.youtube.com/watch?v=3G_yyE5GeIk来帮助我弄清楚如何在单元测试中使用nock。但是我仍然不明白为什么它是不确定的。
我正在测试的原始功能
let axios = require("axios");
let atob = require('atob');
let KARMABOT_API_ENDPOINT = process.env.KARMABOT_API_ENDPOINT;
module.exports = {
getSorted: async function (direction) {
if (direction !== "ASC" && direction !== "DESC") {
console.error("INVALID SORTING DIRECTION: %s. PLEASE PROVIDE ASC OR DESC", direction);
return;
}
try {
let url = `http://${KARMABOT_API_ENDPOINT}/getsorted/${direction}`;
console.log('endpoint is:', KARMABOT_API_ENDPOINT)
console.log('URL IS:', url)
let jsonResult = await axios.get(url);
let sorted = { users: [], karmas: [] };
jsonResult.data.forEach(element => {
//users are stored in the database encoded, atob() decodes them back into strings
sorted.users.push(atob(element[0]));
sorted.karmas.push(element[1]);
});
return sorted
} catch (error) {
console.error('ERROR HERE', error)
}
}
} //end module.exports
单元测试代码:
const assert = require('chai').assert;
const getSorted = require('../src/karma').getSorted;
const nock = require('nock');
let karmaApi = nock('http://server:4567');
describe('Sorting', function () {
it('should return karma in DESC order', function (done) {
let expectedKarmas = { users: ['nikki', 'person', 'nolan'], karmas: ['3', '2', '1'] }
karmaApi.get('/getsorted/DESC')
.reply(200,
[['bmlra2k=', '3'], ['cGVyc29u', '2'], ['bm9sYW4=', '1']]
);
let recievedKarmas = getSorted("DESC");
console.log('recievedKarmas:::', recievedKarmas)
assert.equal(recievedKarmas, expectedKarmas);
});
});
完全错误:
Sorting
endpoint is: undefined
URL IS: http://undefined/getsorted/DESC
recievedKarmas::: Promise { <pending> }
1) should return karma in DESC order
ERROR HERE { Error: getaddrinfo ENOTFOUND undefined undefined:80
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'undefined',
host: 'undefined',
port: 80,
config:
{ url: 'http://undefined/getsorted/DESC',
method: 'get',
headers:
{ Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.19.0' },
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined },
request:
Writable {
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
_events:
[Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError] },
_eventsCount: 2,
_maxListeners: undefined,
_options:
{ protocol: 'http:',
maxRedirects: 21,
maxBodyLength: 10485760,
path: '/getsorted/DESC',
method: 'GET',
headers: [Object],
agent: undefined,
auth: undefined,
hostname: 'undefined',
port: 80,
nativeProtocols: [Object],
pathname: '/getsorted/DESC',
proto: 'http',
host: 'undefined:80' },
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header:
'GET /getsorted/DESC HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: undefined\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/getsorted/DESC',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
_currentUrl: 'http://undefined:80/getsorted/DESC' },
response: undefined,
isAxiosError: true,
toJSON: [Function] }
0 passing (23ms)
1 failing
1) Sorting
should return karma in DESC order:
AssertionError: expected {} to equal { Object (users, karmas) }
at Context.<anonymous> (test/test-karma.js:19:16)
npm ERR! Test failed. See above for more details.
我知道我至少要达到原始功能,因为ERROR HERE
被记录下来了。但是当我从测试中调用主机名时,我看不到如何定义主机名,但是当我运行脚本时,它可以很好地工作。