I have a pretty simple problem but I can’t for the life of me figure out how to make it work, I’ve spent hours looking online..
I’m using the got library to work with a weather API here is the code below:
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 }
The code works perfectly when I run it with node, however when I try and run tests using Jest I get the followig:
C:UsersalfonOneDriveDocumentsCodingJavaScriptthermostatnode_modulesgotdistsourceindex.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)
My issue is that it seems that only the got library has trouble being imported, if I remove it and run Jest dotenv library gets loaded normally. I have no idea what I’m missing here..