简体   繁体   English

如何测试 Jasmine 中的值是否“大于或等于”?

[英]How can I test that a value is “greater than or equal to” in Jasmine?

I want to confirm that a value is a decimal (or 0), so the number should be greater than or equal to zero and less than 1.我想确认一个值是小数(或 0),所以这个数字应该大于或等于 0并且小于 1。

describe('percent',function(){  

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

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

  });

});

How do I mimic " >= 0 "?我如何模仿“ >= 0 ”?

I figured I should update this since the API has changed in newer versions of Jasmine.我想我应该更新它,因为 API 在较新版本的 Jasmine 中发生了变化。 The Jasmine API now has built in functions for: Jasmine API 现在内置了以下功能:

  • toBeGreaterThanOrEqual大于或等于
  • toBeLessThanOrEqual小于或等于

You should use these functions in preference to the advice below.您应该优先使用这些功能而不是下面的建议。

Click here for more information on the Jasmine matchers API单击此处了解有关 Jasmine 匹配器 API 的更多信息


I know that this is an old and solved question, but I noticed that a fairly neat solution was missed.我知道这是一个古老且已解决的问题,但我注意到错过了一个相当简洁的解决方案。 Since greater than or equal to is the inverse of the less than function, Try:由于大于或等于是小于函数的反函数,请尝试:

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

In this approach, the value of percent can be returned by an async function and processed as a part of the control flow.在这种方法中,百分比值可以由异步函数返回并作为控制流的一部分进行处理。

You just need to run the comparison operation first, and then check if it's truthy.您只需要先运行比较操作,然后检查它是否为真。

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

    var percent = insights.percent;

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

  });   
});

Jasmine 的当前版本支持 toBeGreaterThan 和 toBeLessThan。

expect(myVariable).toBeGreaterThan(0);

I'm late to this but posting it just in case some one still visits this question looking for answers, I'm using Jasmine version 3.0 and as mentioned by @Patrizio Rullo you can use toBeGreaterThanOrEqual/toBeLessThanOrEqual .我迟到了,但发布它以防万一有人仍然访问这个问题寻找答案,我使用的是 Jasmine 3.0 版,正如@Patrizio Rullo 所提到的,您可以使用toBeGreaterThanOrEqual/toBeLessThanOrEqual

It was added in version 2.5 as per release notes - https://github.com/jasmine/jasmine/blob/master/release_notes/2.5.0.md它是根据发行说明在 2.5 版中添加的 - https://github.com/jasmine/jasmine/blob/master/release_notes/2.5.0.md

For eg例如

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

or或者

expect(percent).toBeGreaterThanOrEqual(1);

Somewhat strangley this isn't basic functionality有点奇怪,这不是基本功能

You can add a custom matcher like this:您可以像这样添加自定义匹配器:

JasmineExtensions.js 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
                           };
                       }
                   };
               }
    );
};

In effect you're defining a constructor for your matcher - it's a function that returns a matcher object.实际上,您正在为匹配器定义一个构造函数 - 它是一个返回匹配器对象的函数。

Include that before you 'boot'.在“启动”之前包括它。 The basic matchers are loaded at boot time.基本匹配器在启动时加载。

Your html file should look like this:您的 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>

Then in your boot.js add the call to add the matchers after jasmine has been defined but before jasmine.getEnv().然后在您的 boot.js 中添加调用以在定义 jasmine 之后但在 jasmine.getEnv() 之前添加匹配器。 Get env is actually a (slightly misleadingly named) setup call. Get env 实际上是一个(有点误导性的命名)设置调用。

The matchers get setup in the call to setupCoreMatchers in the Env constructor.匹配器在 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();

They show another way of adding custom matchers in the sample tests, however the way it works is to recreate the matcher(s) before every single test using a beforeEach .他们展示了在示例测试中添加自定义匹配器的另一种方法,但是它的工作方式是在每次测试之前使用beforeEach重新创建匹配器。 That seems pretty horrible so I thought I'd go with this approach instead.这看起来很可怕,所以我想我会采用这种方法。

I have run into the same issue today, and as it turns out, it is not that difficult to add a custom matcher for it.我今天遇到了同样的问题,事实证明,为其添加自定义匹配器并不难。 The main advantage of a custom matcher is that it can return meaningful messages when a test fails.自定义匹配器的主要优点是它可以在测试失败时返回有意义的消息。

So here is the code for two matchers, .toBeAtLeast() and .toBeAtMost() , in case it helps someone.所以这里是两个匹配器的代码, .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;
        }
      };
    }

  } );

} );

It was just merged in the Jasmine GitHub master branch my patch to add the matchers you need:它刚刚合并到 Jasmine GitHub master 分支 my patch 中以添加您需要的匹配器:

Add toBeGreatThanOrEqual and toBeLessThanOrEqual matchers 添加 toBeGreatThanOrEqual 和 toBeLessThanOrEqual 匹配器

But I have no idea in which release it will be.但我不知道它将在哪个版本中发布。 In the while, you can try to use the code of my commit in your local Jasmine copy.同时,您可以尝试在您的本地 Jasmine 副本中使用我提交的代码。

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

You can use the function least to check if a value is greater than or equal to some other value.您可以使用least函数检查某个值是否大于或等于某个其他值。

An alias of least is gte (great than or equal to). least的别名是gte (大于或等于)。 Vice versa, you can use lte (less than or equal to) to check the opposite.反之亦然,您可以使用lte (小于或等于)来检查相反的情况。

So, to answer the question, you can do:所以,要回答这个问题,你可以这样做:

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

Using This Updated Formula:使用这个更新的公式:

toBeGreaterThanOrEqual toBeLessThanOrEqual大于或等于小于或等于

Should Work!应该管用!

I am suprised that all people above wasted so much time, to try 'in jasmine way', while jasmine matchers proved over years to be unhandy and cover only basic cases.我很惊讶上面所有的人都浪费了这么多时间来尝试“以茉莉花方式”,而多年来茉莉花匹配器被证明是不方便的,只涵盖基本情况。

Answer with adding custom matcher is even more bad, because it will surprise new developers which will join your team in future, probably no one else than you will use it.添加自定义匹配器的答案更糟糕,因为它会让未来加入您团队的新开发人员感到惊讶,可能除了您之外没有其他人会使用它。

Why not simply为什么不简单

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

    var percent = insights.percent; 
    expect(percent>=0 && percent<1).toBeTruthy();
  });
});

and go forward, and do something useful?继续前进,做一些有用的事情? test case name already is telling you what percent should be.测试用例名称已经告诉你应该是多少百分比。

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

相关问题 TestCafe - 如何检查断言中的值是否大于或等于 - TestCafe - How to check if the value is greater than or equal in the assertion 如何过滤此数组中大于或等于90的标记? - How do I filter marks greater than or equal to 90 in this array? 如何测试一个值是否大于数组中的另一个值。 javascript - how to test if a value is greater than another value in an array. javascript 我如何在茉莉花中测试回调 - How i can test callback in jasmine 量角器和茉莉花:如何测试重定向? - Protractor and Jasmine: How can I test redirects? 如何在Jasmine中通过此测试? - How can I make this test pass in Jasmine? 大于或不等于 - Greater than or not equal to 如果 window 宽度小于给定值,我如何使用 JavaScript 隐藏 Html 中的文本,并在大于该值时显示它 - How can i hide a text in Html using JavaScript if the window width is lower than a given value and show it if it's greater than the value 我如何使用v-for循环显示(如果索引大于VUEJS中的值)(+10) - How can I show (+10 more) if index is greater than value in VUEJS using v-for loop 如果特定单元格的值大于10,该如何触发Google Spreadsheets脚本 - How can I trigger Google Spreadsheets script if a specific cell contains a value greater than, say, 10
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM