简体   繁体   English

如何使用 Jest 为 javascript 揭示模块模式编写单元测试?

[英]How to write unit test for javascript revealing module pattern with Jest?

For example: my math_util.js is例如:我的 math_util.js 是

var MathUtil = function(){
  function add(a,b){
    return a + b;
  }
  return {
    add: add
  };
}

I'll use Jest to test add().我将使用 Jest 来测试 add()。 So I'll write所以我会写

test('add', ()=>{
  expect(MathUtil().add(1,1)).toBe(2);
});

But I get MathUtil is undefined or MathUtil() is not a function.但我得到MathUtil未定义或MathUtil()不是函数。

I also tried to use require() or import .我也尝试使用require()import But MathUtil doesn't have module.export or export .但是MathUtil没有module.exportexport

So how to write unit test for javascript revealing module pattern with Jest?那么如何使用 Jest 为 javascript 揭示模块模式编写单元测试?

Note: I've a project with all scripts written in revealing module pattern so convert all to ES2015 module may not be practical.注意:我有一个项目,所有脚本都以揭示模块模式编写,因此将所有脚本都转换为 ES2015 模块可能不切实际。

If you really want to test math_util.js exactly as it is written you can do this:如果您真的想完全按照编写的方式测试math_util.js ,您可以这样做:

// ---- math_util.test.js ----
const fs = require('fs');
const path = require('path');
const vm = require('vm');

const code = fs.readFileSync(path.join(__dirname, '/math_util.js'), 'utf-8');
const MathUtil = vm.runInThisContext(code + '; MathUtil');

test('add', ()=>{
  expect(MathUtil().add(1,1)).toBe(2);
});

...but best practice would be to refactor the code into modules. ...但最佳实践是将代码重构为模块。 For the revealing module pattern that should be a very straightforward process, just remove the outer wrapping function and returned object, and put export in front of anything that was in the returned object:对于应该是一个非常简单的过程的揭示模块模式,只需删除外部包装函数和返回对象,并将export放在返回对象中的任何内容之前:

// ---- math_utils.js ----
export function add(a,b){
  return a + b;
}


// ---- math_utils.test.js ----
import { add } from './math_utils';

test('add', ()=>{
  expect(add(1,1)).toBe(2);
});

You can use babel-plugin-rewire for this.您可以为此使用babel-plugin-rewire Check this post: https://www.samanthaming.com/journal/2-testing-non-exported-functions/检查这篇文章: https : //www.samanthaming.com/journal/2-testing-non-exported-functions/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM