我有一個現有的異步功能:
async doJSONGetRequest(getUrl, accessToken) {
return new Promise(function(resolve, reject) {
const reqHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
};
console.info('url = ' getUrl);
request.get({
url: getUrl,
headers: reqHeaders,
}, function(err, response) {
if (err) return reject(err);
try {
// console.debug(`response = ${response.body}`);
const parsed = JSON.parse(response.body);
return resolve(parsed);
} catch (err) {
return reject(err);
}
});
});
}
}
我正在嘗試用 Jasmine(v4) 對其進行測驗。當然,我不希望這個東西真正發出 HTTP 請求,所以我嘗試在 'beforeAll' 部分中的 'request' 包的 'get' 函式上安裝一個間諜:
describe('RAPIDAPIService', function() {
beforeAll(async function() {
spyOn(request, 'get')
.and
.callFake(async (parameters) => {
if (parameters.url === 'http://localhost/api/getSomething') {
const rsp = {};
rsp.body = 'good stuff';
return rsp;
} else if (parameters.url === 'http://localhost/api/whoops') {
return new Error('401 not found');
} else {
return null;
}
});
});
it('doJSONGetRequest should run successfully', async () => {
expect(api.doJSONGetRequest).toBeDefined();
const res = await api.doJSONGetRequest('http://localhost/api/getSomething', '12345678');
expect(data).toEqual('good stuff');
});
it('doJSONGetRequest should resolve errors properly', async () => {
expect(api.doJSONGetRequest).toBeDefined();
const res = await api.doJSONGetRequest('http://localhost/api/whoops', '12345678');
const expectedError = new Error('401 not found');
expect(res).toEqual(expectedError);
});
控制臺日志陳述句似乎表明我實際上正在通過“it”測驗中的“await”呼叫/回傳一些東西。但是間諜實際上正在作業/檢測到該網址已被呼叫。
(請注意,我沒有在同一檔案中包括其他不進行異步呼叫并且正在作業的測驗......只是為了讓您知道訪問實際的“api”庫及其函式沒有問題。)
這兩個測驗一直失敗,并顯示“錯誤:超時 - 異步功能未在 5000 毫秒內完成”。就像我說的那樣,他們似乎沒有從呼叫 doJSONGetRequest 函式回傳到測驗。
有什么想法嗎?
謝謝!
uj5u.com熱心網友回復:
我認為問題是嘲笑。request.get似乎需要兩個引數,我認為您需要在完成后呼叫第二個引數(回呼函式),以便resolve可以呼叫。
嘗試這個:
spyOn(request, 'get')
.and
// add callbackFunction as 2nd argument
.callFake((parameters, callbackFunction) => {
if (parameters.url === 'http://localhost/api/getSomething') {
const rsp = {};
rsp.body = 'good stuff';
callbackFunction(null, rsp);
} else if (parameters.url === 'http://localhost/api/whoops') {
callbackFunction({ error: '401 not found' }, {});
} else {
callbackFunction(null, null);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/443541.html
