以下代码如何进行单元测试?
发布于 3年前 作者 fengmk2 1792 次浏览

下面一个方法的代码,如何进行完善的单元测试呢? console.error 你觉得是直接mock还是替换好?还是说这段代码还不具良好的可测试性?

/**
 * add support for <%- partial('view') %> function
 * rather than realtime compiling, this implemention simply statically 'include' the partial view file
 */
var reg_meta = /[\\^$*+?{}.()|\[\]]/g;
var open = ejs.open || "<%";
var close = ejs.close || "%>";
var partial_pattern = new RegExp(open.replace(reg_meta, "\\$&") + 
  "[-=]\\s*partial\\((.+)\\)\\s*" + close.replace(reg_meta, "\\$&"), 'g');

function partial(data, view_name) {
  return data.replace(partial_pattern, function(all, view) {
    view = view.match(/['"](.*)['"]/);    // get the view name
    if (!view || view[1] === view_name) {
      return "";
    } else {
      var view_path = path.join(settings.root, view[1]);
      var tpl = '';
      try {
        tpl = fs.readFileSync(view_path, 'utf-8');
      } catch(e) {
        console.error("[connect-render] Error: cannot load view partial " + view_path);
        return "";
      }
      return partial(tpl, view[1]);
    }
  });
}
1 回复

刚翻了一下module.js 源码,觉得强行插入比较好,哈哈哈

回到顶部