I am migrating a react app to use ES6 syntax. I have a file Utils.js as follows:
export default class Utils {
static getParameterByName(name) {
const paramName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + paramName + '=([^&#]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
static getArrayOfIndices(text, char) {
const resultArray = [];
let index = text.indexOf(char);
const lastIndex = text.lastIndexOf(char);
while (index <= lastIndex && index !== -1) {
resultArray.push(index);
if (index < lastIndex) {
index = text.substr(index + 1).indexOf(char) + index + 1;
} else {
index = lastIndex + 1999; // some random addition to fail test condition on next iteration
}
}
return resultArray;
}
}
This previously was in javascript and I had jest unit tests written for them. However,when I run the tests now I get the error
Utils.getArrayOfIndices is not a function
To run the jest tests on es6 code, I am using the package babel-jest, which transpiles the code so that jest can run it.
When debugging the jest test, when I hover and inspect the Utils object I see that the functions are there but they appear greyed out so perhaps not accessible from outside.
How do I export all these functions using ES6?
====EDIT 1====
After the comments, I changed the file to use default module, as follows:
export default {
getParameterByName: function getParameterByName(name) {
const paramName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + paramName + '=([^&#]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
},
getArrayOfIndices: function getArrayOfIndices(text, char) {
const resultArray = [];
let index = text.indexOf(char);
const lastIndex = text.lastIndexOf(char);
while (index <= lastIndex && index !== -1) {
resultArray.push(index);
if (index < lastIndex) {
index = text.substr(index + 1).indexOf(char) + index + 1;
} else {
index = lastIndex + 1999; // some random addition to fail test condition on next iteration
}
}
return resultArray;
},
}
However, the issue may be by how I am importing the file. I have tried different things. Before the change, the Utils module was referenced in the beforeEach method using require
Utils = require('../Utils')
Later on with the ES6 syntax, I imported the module once at the top of the file as
import Utils from '../Utils';
However, this also throws the same error, albeit with a slightly different message.
TypeError: _Utils2.default.getArrayOfIndices is not a function
I am not quite sure what am I doing wrong.