我正在编写一个在浏览器中使用的数学库,并使用 Jest 对其运行单元测试(我意识到它更适合 Node)。我已经通过扩展 JS Math 解决了大部分问题,但是为了求平均(均值)和标准差,我正在使用 https://mathjs.org的数学图书馆。这在浏览器中一切正常,但 Jest 无法看到 mathjs 库,我不确定如何修复它。
这是在 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
这是驱动它的 HTML:
<script src='js/math.js'></script>
<script src='js/CalRunWebMath.js'></script>
这是 Jest 测试文件:
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);
});
我收到的错误是:ReferenceError: math is not defined (我从上面的代码片段中省略了其他通过的测试):
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
如何在浏览器中公开数学模块以便 Jest 可以在测试中看到它?
最佳答案
Node
中的全局命名空间对象可用作 global
。
您可以像这样将math
添加到全局命名空间对象:
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!
});
关于javascript - 如何在浏览器中公开外部库以便 Jest 单元测试可以看到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55268087/