2017-07-25 103 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(功能)每次測試後運行。 (功能)後的 在最後一次測試後運行。 –