简体   繁体   English

为什么我在使用QUnit编写测试时会使用expect()?

[英]Why Would I ever use expect() When Writing Tests With QUnit?

I've recently started using QUnit to unit test my JavaScript and I'm a little confused by a feature in there documentation: expect() . 我最近开始使用QUnit对我的JavaScript进行单元测试,我对文档中的一个功能有点困惑: expect()

According to the docs, expect() is designed to: 根据文档, expect()旨在:

[s]pecify how many assertions are expected to run within a test. [s]指出在测试中预计会运行多少个断言。

And here's the example they give: 这是他们给出的例子:

test( "a test", function() {
  expect( 2 );

  function calc( x, operation ) {
    return operation( x );
  }

  var result = calc( 2, function( x ) {
    ok( true, "calc() calls operation function" );
    return x * x;
  });

  equal( result, 4, "2 square equals 4" );
});

The only thing I see here is maintenance nightmare. 我唯一看到的是维护噩梦。 Every time you add an assertion to a test, you have to update that number or the test will fail. 每次向测试添加断言时,都必须更新该编号,否则测试将失败。 Is there a practical application for this kind of feature? 这种功能有实际应用吗?

The only thing I see here is maintenance nightmare... Is there a practical application for this kind of feature? 我在这里看到的唯一一件事是维护噩梦......这种功能是否有实际应用?

Well, the way I think expect is meant to be used is with grouped meaningful tasks. 好吧,我认为expect的方式是使用分组有意义的任务。 It's useful for testing events or callbacks, for example: 它对测试事件或回调非常有用,例如:

test('trigger an event', function() {
  expect(1);

  $('div')
    .on('click', function() { ok(1) });
    .trigger('click');
});

It doesn't become a nightmare if you keep meaningful tasks grouped in small tests, where only 2 or 3 assertions are expected. 如果您将有意义的任务分组在小测试中,并且预期只有2或3个断言,那么这不会成为一场噩梦。

It can be used as a safeguard to ensure that you haven't somehow written a test that can't be run. 它可以作为一种安全措施,以确保您没有以某种方式编写无法运行的测试。 If you get into the habit of writing the expected number of tests, should you ever somehow write a test suite where one test is hidden from QUnit for some reason, QUnit will pick this up before you would. 如果你养成了编写预期数量的测试的习惯,你是否应该以某种方式编写一个测试套件,其中一个测试由于某种原因隐藏在QUnit中,QUnit会在你之前选择它。

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

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