Alfonso
Alfonso

Reputation: 149

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

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:\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)

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..

Upvotes: 0

Views: 690

Answers (1)

Alfonso
Alfonso

Reputation: 149

I ended up trying an older version of got (11.8.2), which runs ES35 and that gives no problems at all. I'm guessing maybe the newer version of got which came out one month ago is causing some potential issues?

npm install [email protected]

https://www.npmjs.com/package/got

Upvotes: 3

Related Questions