javascript - 原型(prototype)方法的 JS 单元测试

标签 javascript unit-testing

因为IE8不支持trim(),所以我想有一个后备选项来使用正则表达式(我知道这里有很多例子),所以有这个

function trim(value) {
  if (typeof value === 'string') {
    if (String.prototype.trim) {
      value = value.trim();
    } else {
      value = value.replace(/^\s+|\s+$/g, "");
    }
  }

  return value;
}

我想要做的是为此编写单元测试,所以基本上将 String.prototype.trim 设置为 truefalse 这样我就可以确保使用 native 和正则表达式选项

describe('trim', function() {
  it('should use native trim if available', function(){
    String.prototype.trim = true; // THIS DOES NOT WORK
    var string = 'test string  ';
    expect(string.trim()).toEqual('test string');
  });  
});

我怎样才能做到这一点?

谢谢

最佳答案

在该示例中,您将 String.prototype.trim 重新分配给 bool 值。这意味着您不能再调用 string.trim()。

你可以通过将 String.prototype.trim 指定为 false 来检查你的 polyfill 是否有效,然后调用 trim(string)。

describe('trim', function() {
  it('should use native trim if available', function(){
    String.prototype.trim = false;
     var string = 'test string  ';
    expect(trim(string)).toEqual('test string');
  });  
});

我对重新分配 String 的属性感到非常不舒服,因此您也可以将 ie8 trim 分成一个单独的函数,然后可以更轻松地测试它。

function ie8Trim(value) {
  if (typeof value === 'string') {
   return value.replace(/^\s+|\s+$/g, "")
  }
  return value
}

function trim(value) {
  if (typeof value === 'string') {
    if (String.prototype.trim) {
      return value.trim();
    } else {
      return ie8Trim(value)
    }
  }
  return value;
}

关于javascript - 原型(prototype)方法的 JS 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41762656/

相关文章:

javascript - 使用 Angular/Cordova 上传文件

c# - 单元测试时我应该使用模拟对象吗?

java - 当使用多个 TestNG 组时,Infinitest 不会运行 @Before{Method,Class} 方法

c# - 如何对依赖于 HttpContext.GetGlobalResourceObject 的类进行单元测试?

javascript - jQuery 将相同的类添加到两个不同容器中的相同元素索引

javascript - 你能制作一个对象 'callable' 吗?

javascript - 如何对在其依赖项上注册回调的 Angular 服务进行单元测试?

unit-testing - 如何使用 visual studio 2012 执行系统或集成测试而不将它们包含在运行所有测试中?

javascript - 在 MediaWiki 站点上通过 JS 更改 URL 字符串

javascript - 将 jQuery Draggable() 元素移动到新的父元素