Cannot parse file with mocha

Viewed 178

Why in mocha my parser returns an error, but in vanilla JS it works well? This is my parser that I keep in a separate file, it should parse CSV file and extract value from there.

parser.js:

const fetch = require("node-fetch");

module.exports = async function(num) {
    const response = await fetch('../date.csv');
    const data = await response.text();
    let rows = data.split('\n');
    let res = rows[0].split(',');
    return res[num];
}

date.csv file:

1,?start=2013-09-01&end=2013-09-05,SomeInfo,false
2,?start=2014-09-01&end=2014-09-05,SomeInfo,false

Mocha test:

let file = require('../utils/parser');
let param = file(1);

describe('Account', () => {
    it('Print', () => {
        console.log(param);
       });
   });

Logs:

Account
Promise {
  <rejected> TypeError: Only absolute URLs are supported
      at getNodeRequestOptions (node_modules/node-fetch/lib/index.js:1305:9)
1 Answers

You should provide an absolute url to the file.

For example, before starting the tests, set some environment variable so that it points to the root url of your server:

package.json

"scripts": {
  ...
  "test": "BASE_URL='http://127.0.0.1:8080' mocha"
  ...
}

And then in the code do something like this:

parser.js

const fetch = require("node-fetch");

module.exports = async function(num) {
    const absPath = process.env.BASE_URL + '../date.csv'
    const response = await fetch(absPath);
    const data = await response.text();
    let rows = data.split('\n');
    let res = rows[0].split(',');
    return res[num];
}

Or use url.pathToFileURL from node's core package "url" (Added in node version v10.12.0)

Related