簡體   English   中英

開玩笑無法加載獲取庫進行測試-'SyntaxError:無法在模塊外使用導入語句'

[英]Jest unable to load got libary for testing - 'SyntaxError: Cannot use import statement outside a module'

我有一個非常簡單的問題,但我一生都無法弄清楚如何讓它工作,我已經花了幾個小時在網上尋找..

我正在使用 got 庫來處理天氣 API 這是下面的代碼:

 import got from 'got'; import dotenv from 'dotenv'; dotenv.config(); class WeatherApi { #getApiKey = () => process.env.WEATHER_API; fetchWeatherData = (city, callback) => { const apiKey = this.#getApiKey(); const apiUrl = `http://api.openweathermap.org/data/2.5/weather?units=metric&q=${city}&appid=${apiKey}`; got(apiUrl).then((response) => { const weatherData = JSON.parse(response.body); callback(weatherData) }); } } export { WeatherApi }

當我使用節點運行代碼時,代碼運行良好,但是當我嘗試使用Jest運行測試時,我得到以下信息:

 C:\Users\alfon\OneDrive\Documents\Coding\JavaScript\thermostat\node_modules\got\dist\source\index.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import create from './create.js'; ^^^^^^ SyntaxError: Cannot use import statement outside a module > 1 | import got from 'got'; | ^ 2 | import dotenv from 'dotenv'; 3 | dotenv.config(); 4 | at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14) at Object.<anonymous> (weather_api.js:1:1)

我的問題是,似乎只有 got 庫無法導入,如果我刪除它並運行 Jest dotenv 庫會正常加載。 我不知道我在這里錯過了什么..

我最終嘗試了一個舊版本的 got (11.8.2),它運行 ES35,完全沒有問題。 我猜也許一個月前發布的新版本 got 引起了一些潛在的問題?

 npm install got@11.8.2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM