Home > Blockchain >  Why isn't require() working for my constants exported into a node.js modules?
Why isn't require() working for my constants exported into a node.js modules?

Time:01-06

I am trying to run this test in Jest:

test("find the earliest start", () => {
  expect(findEarliestStart([ex.TS2])).toBe(ex.TS2.start_time);
  expect(findEarliestStart([ex.TS5, ex.TS2, ex.TS6])).toBe(ex.TS5.start_time);
});

I have this require in the test file: const ex = require("constants");

I get the error that TS2 is undefined, specifically "TypeError: Cannot read property 'start_time' of undefined".

In constants.ts I have:

const TS2: Timeslot = 
{start_time: 940,
  end_time: 980,
  day: "Wed",
  term: "2"
}

const TS5: Timeslot = 
{start_time: 180,
  end_time: 210,
  day: "Wed",
  term: "2"
}

const TS6: Timeslot = 
{start_time: 250,
  end_time: 310,
  day: "Wed",
  term: "2"
}

and

module.exports = {
  TS2:TS2, TS5:TS5, TS6:TS6
}

The function findEarliestStart looks like this:

/**
 * return the earliest start time out of all timeslots
 * @param {Timeslot[]} lots 
 */
export const findEarliestStart = (lots:Timeslot[]): Time => {
  if(!lots.length){
    throw new Error("cannot find earliest start of empty array");
  };
  return lots.reduce((min:number, ts:Timeslot) => {
    return (ts.start_time < min) ? ts.start_time : min
  },
  Number.MAX_VALUE)

CodePudding user response:

First of, Hello and Welcome on stackoverflow, @ptellier!

TL;DR: useconst ex = require("./constants"); with "./" in front of the constants.

The require in node has some syntax to be aware of. Normally, it is used to require components and modules from external packages, installed using a package manager. In this case, the name of the corresponding package is supplied as an argument. If the package is part of a namespace, it starts with @namespace/packagename, otherwise it is just the packagename.

To load local files, you have to tell node that you are looking for a local file instead of a package. You can do this by using relative path prefixes like ./ for files in the same directory as the current file or ../ to start in the current folders parent directory.

Since you were missing the path prefix, node loaded its internal constants module, which apparently has no TS* properties, which is why they were undefined.

  •  Tags:  
  • Related