【问题标题】:How can I test that a value is "greater than or equal to" in Jasmine?如何测试 Jasmine 中的值是否“大于或等于”?
【发布时间】:2014-06-06 20:41:11
【问题描述】:

我想确认一个值是小数(或0),所以该数字应该大于或等于零并且小于1。

describe('percent',function(){  

  it('should be a decimal', function() {

    var percent = insights.percent; 
    expect(percent).toBeGreaterThan(0);
    expect(percent).toBeLessThan(1);

  });

});

如何模仿“>= 0”?

【问题讨论】:

标签: javascript tdd jasmine


【解决方案1】:

我想我应该更新这个,因为 API 在新版本的 Jasmine 中发生了变化。 Jasmine API 现在已内置函数:

  • toBeGreaterThanOrEqual
  • toBeLessThanOrEqual

您应该优先使用这些功能而不是下面的建议。

Click here for more information on the Jasmine matchers API


我知道这是一个古老且已解决的问题,但我注意到错过了一个相当简洁的解决方案。由于大于等于是小于函数的逆函数,试试:

expect(percent).not.toBeLessThan(0);

在这种方法中,百分比的值可以由异步函数返回并作为控制流的一部分进行处理。

【讨论】:

  • 这一个应该被接受的答案。另外:expect(2 + 2).not.toBe(5)expect(2 + 2).toBeGreaterThan(0)expect(2 + 2).toBeLessThan(5)
  • 这很危险,因为expect(NaN).not.toBeLessThan(0); 通过而不是失败。 (如果你假设percent 是一个数字,not.toBeLessThan 只是逆向。否则,它不是逆向。)
  • 正如@KristianHanekamp 所指出的那样,expect 是不可靠的,因为当 'percent' 的值不是数字 (NaN) 时它也会通过。
【解决方案2】:

您只需要先运行比较操作,然后检查它是否为真。

describe('percent',function(){
  it('should be a decimal',function(){

    var percent = insights.percent;

    expect(percent >= 0).toBeTruthy();
    expect(percent).toBeLessThan(1);

  });   
});

【讨论】:

  • 这行得通,但不幸的是,失败的 ">=" 测试所产生的消息不是特别有表达力(“预期为真假”)。顺便说一句,测试不需要异步(好吧,只是挑剔;)。
  • @hashchange 使用jasmine2-custom-message等插件,可以自定义错误信息:since('expected percent to be greater than or equal to zero').expect(percent >= 0).toBeTruthy();
  • @TachyonVortex 听起来很有趣!我不知道那件事。对于像>= 这样的常见比较,我更喜欢自定义匹配器,因为它可以使测试保持整洁(很容易做到,请参阅下面的答案),但对于出现频率较低或不够表达的比较,该插件似乎是完全正确的事情。谢谢!
  • expect(percent).toBeGreaterThan(-1);xD 我没试过
【解决方案3】:

Jasmine 当前版本支持 toBeGreaterThan 和 toBeLessThan。

expect(myVariable).toBeGreaterThan(0);

【讨论】:

  • 问题问“大于或等于”
【解决方案4】:

我迟到了,但发布它以防万一有人仍然访问这个问题寻找答案,我使用 Jasmine 3.0 版,正如@Patrizio Rullo 所述,您可以使用 toBeGreaterThanOrEqual/toBeLessThanOrEqual强>.

它是根据发行说明在 2.5 版中添加的 - https://github.com/jasmine/jasmine/blob/master/release_notes/2.5.0.md

例如

expect(percent).toBeGreaterThanOrEqual(1,"This is optional expect failure message");

expect(percent).toBeGreaterThanOrEqual(1);

【讨论】:

  • 我认为 jasmine 版本 > 2.3.4 没有按顺序执行规范。因此,如果他们想要规格有序,那么他们可以创建自定义匹配器,但如果他们对无序规格没问题,那么他们可以选择上述版本。
【解决方案5】:

有点奇怪,这不是基本功能

您可以像这样添加自定义匹配器:

JasmineExtensions.js

yourGlobal.addExtraMatchers = function () {
    var addMatcher = function (name, func) {
        func.name = name;
        jasmine.matchers[name] = func;
    };

    addMatcher("toBeGreaterThanOrEqualTo", function () {
                   return {
                       compare: function (actual, expected) {
                           return {
                               pass: actual >= expected
                           };
                       }
                   };
               }
    );
};

实际上,您正在为匹配器定义一个构造函数 - 它是一个返回匹配器对象的函数。

在“启动”之前将其包含在内。基本匹配器在启动时加载。

您的 html 文件应如下所示:

<!-- jasmine test framework-->
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>

<!-- custom matchers -->
<script type="text/javascript" src="Tests/JasmineExtensions.js"></script>
<!-- initialisation-->
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>

然后在您的 boot.js 中添加调用以在定义 jasmine 之后但在 jasmine.getEnv() 之前添加匹配器。 Get env 实际上是一个(有点误导性的)设置调用。

匹配器在 Env 构造函数的 setupCoreMatchers 调用中得到设置。

/**
 * ## Require &amp; Instantiate
 *
 * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
 */
window.jasmine = jasmineRequire.core(jasmineRequire);
yourGlobal.addExtraMatchers();

/**
 * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
 */
jasmineRequire.html(jasmine);

/**
 * Create the Jasmine environment. This is used to run all specs in a project.
 */
var env = jasmine.getEnv();

他们展示了在示例测试中添加自定义匹配器的另一种方法,但是它的工作方式是在每次测试之前使用 beforeEach 重新创建匹配器。这看起来很可怕,所以我想我会改用这种方法。

【讨论】:

    【解决方案6】:

    我今天遇到了同样的问题,事实证明,为其添加自定义匹配器并不难。自定义匹配器的主要优点是它可以在测试失败时返回有意义的消息。

    这里是两个匹配器的代码,.toBeAtLeast().toBeAtMost(),以防它对某人有所帮助。

    beforeEach( function () {
    
      // When beforeEach is called outside of a `describe` scope, the matchers are
      // available globally. See http://stackoverflow.com/a/11942151/508355
    
      jasmine.addMatchers( {
    
        toBeAtLeast: function () {
          return {
            compare: function ( actual, expected ) {
              var result = {};
              result.pass = actual >= expected;
              if ( result.pass ) {
                result.message = "Expected " + actual + " to be less than " + expected;
              } else {
                result.message = "Expected " + actual + " to be at least " + expected;
              }
              return result;
            }
          };
        },
    
        toBeAtMost: function () {
          return {
            compare: function ( actual, expected ) {
              var result = {};
              result.pass = actual <= expected;
              if ( result.pass ) {
                result.message = "Expected " + actual + " to be greater than " + expected;
              } else {
                result.message = "Expected " + actual + " to be at most " + expected;
              }
              return result;
            }
          };
        }
    
      } );
    
    } );
    

    【讨论】:

      【解决方案7】:

      它刚刚合并到 Jasmine GitHub master 分支我的补丁以添加您需要的匹配器:

      Add toBeGreatThanOrEqual and toBeLessThanOrEqual matchers

      但我不知道它会在哪个版本中发布。在此期间,您可以尝试在本地 Jasmine 副本中使用我提交的代码。

      【解决方案8】:

      使用这个更新的公式:

      toBeGreaterThanOrEqual toBeLessThanOrEqual

      应该工作!

      【讨论】:

        【解决方案9】:

        我推荐使用这个 Jasmine 插件: https://github.com/JamieMason/Jasmine-Matchers

        【讨论】:

        • 它包含一个“范围内”匹配器,但不包含一个“大于或等于”/“小于或等于”匹配器...
        • @Vegar,你可以使用 expect(number).toBeGreaterThan(number);
        【解决方案10】:

        您可以使用函数least 来检查一个值是否大于或等于某个其他值。

        least 的别名是gte(大于或等于)。反之亦然,可以用lte(小于等于)来检查相反的情况。

        所以,要回答这个问题,你可以这样做:

        expect(percent).to.be.gte(0)

        【讨论】:

        • 您使用哪个版本的 Jasmine?我刚刚从 2.6.2 升级到 2.8,我仍然收到错误 TypeError: Cannot read property 'be' of undefined for expect(1).to.be.gte(-1);
        猜你喜欢
        • 2010-12-26
        • 2021-11-25
        • 2017-02-28
        • 2010-10-06
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 2016-09-25
        • 2011-08-16
        相关资源
        最近更新 更多