mardi 17 novembre 2020

Jest global variables with require modules

I'm working on some test for a very small vanilla js library, so I have this module

var otherModule = require('../module/mymodule');
var postscribe = require('postscribe');
var exports = module.exports = {};

var API_URL = URL;

exports.myFunction = function (arg1, arg2, arg3) {
  if (arg1 && arg2) {
    var myUrl = getApiUrl(arg1, arg2, arg3);
    callSomeURL(myUrl);
  }
}

function getApiUrl(arg1, arg2, arg3) {
  var param1 = otherModule.getParams(arg1);
  var param2 = otherModule.getOtherParams(arg1);
  return `${API_URL}/v1/pixels/${arg1}/${arg2}${param1}${pdCookie}`;
}

...

then I have otherModule module with my functions

var GLOBAL_VALUE = GLOBAL_VALUE;
var otherModule = {};

otherModule.getParams = function (arg1) {
  return arg1 ? `&value=${arg1}` : '';
}

cookies.getOtherParams = function (arg1) {
  return GLOBAL_VALUE + arg1
}

module.exports = otherModule;

And my webpack configs

const { DefinePlugin } = require('webpack');
const { merge } = require('webpack-merge');

const common = require('./webpack.common.js');
const devConfig = require('./src/config/dev');

module.exports = () => {
  var envConfig = devConfig;

  return merge(common, {
    mode: 'development',
    devtool: 'inline-source-map',
    plugins: [
      new DefinePlugin({
        __DEV__: true,
        URL: JSON.stringify(envConfig.URL),
        GLOBAL_VALUE: JSON.stringify(envConfig.GLOBAL_VALUE)
      })
    ]
  })
}

my common is:

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  plugins: [
    new CleanWebpackPlugin()
  ],
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

And my jest.config

const config = require('./src/config/dev');

module.exports = {
  globals: {
    "GLOBAL_VALUE": config.GLOBAL_VALUE,
    "URL" : config.URL
  }
}

my problem appears when I try to test exports.myFunction via rewire to have access to private function getApiUrl it seems that I can't access to the imported global values, like GLOBAL_VALUE in my myOther, I keep getting ReferenceError: GLOBAL_VALUE is not defined, but when I test myOther module directly everything seems to work, can someone throw some light or resources on what I'm doing wrong?

Aucun commentaire:

Enregistrer un commentaire