2017-07-25 205 views
1

嗨,伙计, 目前我正在测试我的JavaScript代码与Qunit测试框架。我无法在QUnit.test函数中访问我的QUnit.module设置变量。访问Qunit模块安装变量

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未定义

+0

这是行不通的,QUnit不工作的方式。但更重要的是,你为什么要在测试中选择元素? – jakerella

+0

@jakerella我需要为许多测试用例使用该输入元素。所以为了减少一些冗余,我将元素存储在变量(this.inputsticky)中,并在必要时调用相同的元素。 –

+0

是的......但我认为QUnit不会像'this'那样工作。您可以简单地在模块外面定义一个变量。我会为此添加一个答案 – jakerella

回答

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

})(); 
+0

嗨Jakerella, 我在qunit文件队友中实现了相同的功能。仍然没有工作。如果你有一段时间可以请你看看我的代码。我已经更新了我的github链接如下: https://github.com/haripery/unitTest_JS_Qunit –

+0

如果这不起作用,那么问题不在于选择元素。尝试注销'.css()'调用的值。 – jakerella

+1

嗨jakeralla, 我已经用你的想法取代了beforeEach的设置,现在它终于起作用了。谢谢。 –

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

})(); 
+0

Qunit已将以下设置替换为: before(function)在第一次测试之前运行。 beforeEach(function)在每次测试之前运行。 afterEach(功能)每次测试后运行。 (功能)后的 在最后一次测试后运行。 –