Reputation: 732
I am reading a a file using import.meta to resolve the directory which fails when trying to mock it in a function. Here is the part of the code which I want to mock
// readFileUtil
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export async function readFile(fileName: string){
try {
const data = await fs.promises.readFile(fileName, 'utf8')
return data
} catch (err) {
console.log(err);
}
}
I am then using the code above to read a file like this in some code:
import readFileUtils from '../file-utils'
import dataProcessor from '../data/processor
function processData(fileName:string){
const data = await fs.promises.readFile(fileName, 'utf8')
//rest of code uses data
}
I then wrote a Jest test which tests the processData function like this
import readFileUtils from '../file-utils'
import dataProcessor from '../data/processor
jest.mock('../file-utils)'
describe('Data Processing suite' () => {
const fileName = 'resources/data.xml
processData(fileName)
}
Unfortunately I get the following error
The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022'...etc
I have no idea how to solve this issue. I did a lot of online searches but everything I tried does not work. I did the following:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
...
I also installed 'npm install ts-jest-mock-import-meta' but none of these solutions worked
Please help
Upvotes: -1
Views: 620
Reputation: 732
I was able to get solve the import.meta error issue. By doing the following.
First, I installed the following
npm install @babel/preset-typescript --save-dev
Next, I added created a file, babel.config.js and added the following code;
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript",
],
};
I am still unable to get the mocking of the file reading function to work.
Upvotes: 1