I want to do Javascript unit tests.
I want to load a local file sample.js from testCalc.js below and call a function in sample.js
How can I change it?

Error message

I want to do a unit test with mocha, but I can't call a function written in the Javascript file to be tested.

Error message
% mocha testCalc.js

  sample test
    1) sample test

  0 passing (7ms)
  1 failing
  1) sample test
       sample test:
     ReferenceError: calc is not defined
Applicable source code
// testCalc.js
var assert = require ("assert")
var sample = require ("/ home/user/app/web/js/sample.js")
describe ('sample test', function () {
    it ('sample test', function () {
        assert.equal (calc (1), 2, 'testing');
// sample.js
function calc (a, b) {
  return a + b;

import Sample from"/home/user/app/web/js/sample.js"

import Sample from"/home/user/app/web/js/sample.js"
SyntaxError: Unexpected identifier

Supplemental information (FW/tool version etc.)

* Because the purpose is to protect legacy code with tests as much as possible, it is an environment where export and class cannot be added.

OS: debian8
node: v10.8.0

  name: app,
  version: 1.0.0,
  description: "",
  main: index.js,
  directories: {
    test: tests
  scripts: {
    test: echo \ "Error: no test specified \"&&exit 1
  author: "",
  license: ISC,
  devDependencies: {
    assert: ^ 1.4.1,
    mocha: ^ 5.2.0,
    mocha-webpack: ^ 1.1.0,
    webpack: ^ 4.17.1
  • Answer # 1

    To test private functions that are not exported
    I think npm's rewire module can be used.


  • Answer # 2

    Is this because the calc function is not exported?

    export function calc (a, b) {
      return a + b;