访问Qunit模块设置变量

时间:2017-07-25 18:31:28

标签: javascript jquery unit-testing qunit

嗨,大家好, 目前我正在使用Qunit Testing框架测试我的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未定义

2 个答案:

答案 0 :(得分:0)

根据评论,如果您只想保留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 !" );
  });

})();

答案 1 :(得分:0)

(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 !" );
  });

})();