How to expose external library in browser so Jest

2019-08-10 04:14发布

I'm writing a math library to be used in a browser, and using Jest to run unit tests on it (which I realize is more geared toward Node). I've solved most of the issues by extending JS Math, but in order to do averaging (mean) and standard deviation, I'm working with https://mathjs.org's math library. This all works fine in the browser, but Jest is unable to see the mathjs library and I'm not sure how to fix it.

This is the particular section of code that's failing in Jest (CalRunWebMath.js):

//Extend Math to calculate coefficient of variation:
Math.cv = function(numericArray){
    var std = math.std(numericArray);
    var mean = math.mean(numericArray);
    //this is how I originally did it:
    //return math.std(numericArray)/math.mean(numericArray);
    return std/mean;
}
try {
    module.exports.cv = exports = Math.cv;
}
catch (e) {}

//and this is a snippet of the internal tests that works just fine in the browser, but not in Jest
var data1 = [10.4,20.3,30.2,40.1];
console.log(Math.cv(data1)); //0.5061720808904743

This is the HTML that drives it:

<script src='js/math.js'></script>
<script src='js/CalRunWebMath.js'></script>

This is the Jest test file:

const crwm = require('./CalRunWebMath.js');
const math = require('./math.js');
const cv = crwm.cv;

test('Calculates coefficient of variation', ()=> {
    var data1 = [10.4,20.3,30.2,40.1];
    expect(cv(data1)).toBe(0.5061720808904743);
});

The error I receive is: ReferenceError: math is not defined (I've omitted the other passing tests from the snippet above):

 FAIL  ./CalRunWebMath.test.js
  √ Calculates slope of two coordinates (6ms)
  × Calculates coefficient of variation (4ms)
  √ Calculates Y-intercept of two coordinates (1ms)
  √ Calculates the mean of an array of decimals (48ms)

  ● Calculates coefficient of variation

    ReferenceError: math is not defined

      43 | Math.cv = function(numericArray){
      44 |      //console.log(math.std);
    > 45 |      var std = math.std(numericArray);
         |                ^
      46 |      var mean = math.mean(numericArray);
      47 |      //return math.std(numericArray)/math.mean(numericArray);
      48 |      return std/mean;

      at math (js/CalRunWebMath.js:45:12)
      at Object.cv (js/CalRunWebMath.test.js:14:9)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 3 passed, 4 total

How can I expose the math module in the browser so that Jest can see it in the tests?

1条回答
乱世女痞
2楼-- · 2019-08-10 04:58

The global namespace object in Node is available as global.

You can add math to the global namespace object like this:

global.math = require('./math.js');
const { cv } = require('./CalRunWebMath.js');

test('Calculates coefficient of variation', () => {
  var data1 = [10.4, 20.3, 30.2, 40.1];
  expect(cv(data1)).toBe(0.5061720808904743);  // Success!
});
查看更多
登录 后发表回答