2013-12-08 71 views
3

最近我開始使用JS和mocha。使用摩卡重複使用場景

我已經寫了一些測試,但現在我已經到了需要重新使用我已經寫好的測試的時候了。

我已經厭倦了尋找「它」 /「描述」重用,但沒有找到有用的東西......

有誰有一些很好的例子嗎?

感謝

回答

6

考慮如果你只用做單元測試,你不會因爲你的組件之間的集成問題而發現錯誤,你在某個時候測試你的組件。轉儲摩卡運行這些測試將是一個恥辱。所以你可能想用摩卡運行一些測試,它們遵循相同的一般模式,但在一些小方面有所不同。

我發現這個問題的方式是動態創建我的測試函數。它看起來像這樣:

describe("foo", function() { 
    function makeTest(paramA, paramB, ...) { 
     return function() { 
      // perform the test on the basis of paramA, paramB, ... 
     }; 
    } 

    it("test that foo does bar", makeTest("foo_bar.txt", "foo_bar_expected.txt", ...)); 
    it("test what when baz, then toto", makeTest("when_baz_toto.txt", "totoplex.txt", ...)); 
    [...] 
}); 

你可以看到一個真實的例子here

請注意,沒有任何東西會強制您將makeTest功能置於describe範圍內。如果你有一種你認爲足夠普遍的測試,可以將它放在一個模塊中,並且它可以被使用。

0

考慮到各個測試只是用來測試單個功能/單元,一般要避免重複使用你的測試。最好保持每個測試獨立,儘量減少測試的依賴性。

也就是說,如果你有什麼事情你在測試中經常重複,你可以使用一個beforeEach讓事情變得更簡潔

describe("Something", function() { 

    // declare your reusable var 
    var something; 

    // this gets called before each test 
    beforeEach(function() { 
    something = new Something(); 
    }); 

    // use the reusable var in each test 
    it("should say hello", function() { 
    var msg = something.hello(); 
    assert.equal(msg, "hello"); 
    }); 

    // use it again here... 
    it("should say bye", function() { 
    var msg = something.bye(); 
    assert.equal(msg, "bye"); 
    }); 

}); 

你甚至可以使用異步beforeEach

beforeEach(function(done) { 
    something = new Something(); 

    // function that takes a while 
    something.init(123, done); 
});