我正在開發一個使用 API 的小應用程式。我想進行測驗以查看該功能是否按預期作業。該功能有效,但在測驗中,該功能將無法完成并因此失敗。我已經在堆疊溢位和 youtube 上看了幾個小時,但我仍然沒有讓它作業。
這是我的測驗用例:
import * as API from './geonames';
test('Get the country code from sweden', async () => {
return API.getCountryCode("Sweden").then(res => console.log(res));
}, 5000);
這是我的功能:
export async function getCountryCode(country: string): Promise<any> {
// uses the ninja API to get the country code
var url = 'https://api.api-ninjas.com/v1/country?name=' country;
try {
console.log("Before res"); // this runs in my test
let res = await fetch(url, { headers: {'X-Api-Key': API_NINJA_KEY}});
console.log("After res"); // this does not run in my test
let data = await res.json();
console.log("After data")
var countryCode = data[0]['iso2'];
return countryCode
} catch (e) {
}
}
uj5u.com熱心網友回復:
我認為問題在于fetch()功能。在客戶端它存在(在瀏覽器中)但nodejs它不存在。由于您添加了一個try/catch塊,因此錯誤會被默默地忽略。
首先,記錄錯誤!!,不記錄錯誤真的很危險。只要您在開發環境中,通常更喜歡在任何地方記錄它。
export async function getCountryCode(country: string): Promise<any> {
// uses the ninja API to get the country code
var url = 'https://api.api-ninjas.com/v1/country?name=' country;
try {
console.log("Before res"); // this runs in my test
let res = await fetch(url, { headers: {'X-Api-Key': API_NINJA_KEY}});
console.log("After res"); // this does not run in my test
let data = await res.json();
console.log("After data")
var countryCode = data[0]['iso2'];
return countryCode
} catch (e) {
/// Always log or throw an error, never silent!!
console.error('GetCountryCode() failed..', e)
}
}
解決方案
您需要使用其他一些庫來獲取測驗。因此,為了getCountryCode()在瀏覽器和代碼中理想地作業,創建一個幫助函式來獲取正確的請求。我什至建議創建一個您始終使用的通用請求功能。
例如:
// Use any module on serverside you want. I suggest axios
import axios from 'axios'
// Always run all http requests over this function
// The function decides which implementation to use.
const get_requester = () => {
// if fetch present, return it!
if (window && typeof fetch === 'function') {
return fetch
}
return axios
}
const requestApi = (url: string, opts: Object) => {
const request = get_requester()
// do request.. You may need to modify a little
request(url, opts)
}
然后getCountryCode()像這樣使用它:
// ... import request
export async function getCountryCode(country: string): Promise<any> {
// uses the ninja API to get the country code
var url = 'https://api.api-ninjas.com/v1/country?name=' country;
try {
console.log("Before res"); // this runs in my test
// make use of request api
let res = await requestApi(url, {
headers: {'X-Api-Key': API_NINJA_KEY},
method: 'GET'
});
console.log("After res"); // this does not run in my test
let data = await res.json();
console.log("After data")
var countryCode = data[0]['iso2'];
return countryCode
} catch (e) {
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477785.html
