zyxue zyxue - 1 month ago 7
Javascript Question

How to test a function in var in javascript

Given a piece of code like below, which is adopted from reinforcejs

var RL = {};
(function(global) {
var sampleWeighted = function(p) {
var r = Math.random();
var c = 0.0; // cumulative prob
for(var i=0, n=p.length; i<n; i++) {
c += p[i];
if (c >= r) { return i; }
}
// assert(false) may happen if sum(p) < 1;
assert(false, 'wtf');
};

// many content omitted
...
})(RL);

export default RL;


How can I access sampleWeighted and test it, please? I have tried below

import RL from './rl.js';

it('sampleWeighted', () => {
expect(RL.sampleWeighted([0.5, 0.5])).toEqual(1);
});


But it complains with error

FAIL src/lib/rl.test.js
✕ sampleWeighted (1ms)

● sampleWeighted

TypeError: _rl.RL.sampleWeighted is not a function

at Object.<anonymous> (src/lib/rl.test.js:7:46)
at process._tickCallback (internal/process/next_tick.js:103:7)


I am new to javascript testing. Currently, I am using create-react-app to setup the testing framework. So what's the proper way to test the above function, please? If you happened to understand what
sampleWeighted
does, please feel free to comment on it, too.

Answer

sampleWeighted is in the closure of your IIFE (Immediate function invocation syntax)

this way you could keep your method private like private public in Java, notice you have pass the global which is RL, you can treat that as your namespace, and if you want to call sampleWeighted, you need to attach sampleWeighted to RL,

...
RL.sampleWeighted = function() {}
...
Comments