【问题标题】:Accessing Qunit Module setup variables访问 Qunit 模块设置变量
【发布时间】:2017-07-25 18:31:27
【问题描述】:

大家好, 目前我正在使用 Qunit 测试框架测试我的 javascript 代码。我无法在 QUnit.test 函数中访问我的 QUnit.module 设置变量。

QUnit.module( "Module A:Build Notes",{
    setup: function () {
        this.inputsticky = $("input[name=stickyinput]");
    }
});
QUnit.test("Test Case 1",function (assert) {
    assert.expect(1);            
    orangeClick(); //changing color                                                    
    assert.equal( this.inputsticky.css('background-color'),'rgb(255, 165, 0)', "orange Function passed !" );
});

结果: this.inputsticky 未定义

【问题讨论】:

  • 那不行,QUnit 不能那样工作。但更重要的是,您为什么要这样做而不是只选择测试中的元素?
  • @jakerella 我需要在许多测试用例中使用该输入元素。因此,为了减少一些冗余,我只是将元素存储在变量(this.inputsticky)中,并在必要时调用它。
  • 是的...但我认为 QUnit 不适用于 this。您可以简单地在模块之外定义一个变量。我会为此添加一个答案

标签: javascript jquery unit-testing qunit


【解决方案1】:

根据 cmets,如果您只想保留 HTML 元素,您可以完全在模块之外创建一个变量。使用this 并不会真正起作用(据我所知):

(function() {
  // put things in an IIFE to prevent data leakage

  let inputElement;  // define the variable at a higher scope

  QUnit.module( "Module A:Build Notes",{
    setup: function () {
      // now we can set the variable's value for use in all later tests
      inputElement = $("input[name=stickyinput]");
    }
  });
  QUnit.test("Test Case 1",function (assert) {
    assert.expect(1);            
    orangeClick(); //changing color                                                    
    assert.equal( inputElement.css('background-color'),'rgb(255, 165, 0)', "orange Function passed !" );
  });

})();

【讨论】:

  • 嗨 Jakerella,我在我的 qunit 文件伙伴中实现了相同的功能。仍然无法正常工作。如果您有时间,请查看我的代码。我在下面更新了我的 github 链接:github.com/haripery/unitTest_JS_Qunit
  • 如果这不起作用,那么问题不在于选择元素。尝试注销.css() 调用的值。
  • 嗨 jakeralla,我已经用你的想法用 beforeEach 替换了 setup,现在它终于可以工作了。谢谢。
【解决方案2】:
(function() {


  var inputElement;  // define the variable at a higher scope

  QUnit.module( "Module A:Build Notes",{
    beforeEach: function () {
      // now we can set the variable's value for use in all later tests
      inputSticky = $("input[name=stickyinput]");
    }
  });
  QUnit.test("Test Case 1",function (assert) {
    assert.expect(1);            
    orangeClick(); //changing color                                                    
    assert.equal( inputSticky.css('background-color'),'rgb(255, 165, 0)', "orange Function passed !" );
  });

})();

【讨论】:

  • Qunit 已将设置替换为以下内容: before (function) 在第一次测试之前运行。 beforeEach(function) 在每次测试之前运行。 afterEach (function) 在每次测试后运行。 after (function) 在最后一次测试之后运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多