2012-05-12 17 views
46

मैं अब जावास्क्रिप्ट यूनिट-परीक्षण के लिए मोचा का उपयोग कर रहा हूं।मोचा के लिए ग्लोबल 'पहले' और 'पहले से पहले'?

मेरे पास कई परीक्षण फ़ाइलें हैं, प्रत्येक फ़ाइल में before और beforeEach है, लेकिन वे बिल्कुल वही हैं।

मैं उन सभी के लिए वैश्विक before और beforeEach कैसे प्रदान करूं (या उनमें से कुछ)?

उत्तर

26

एक अलग फ़ाइल में before या beforeEach घोषित करें (मैं spec_helper.coffee का उपयोग करता हूं) और इसकी आवश्यकता होती है।

spec_helper.coffee

afterEach (done) -> 
    async.parallel [ 
    (cb) -> Listing.remove {}, cb 
    (cb) -> Server.remove {}, cb 
    ], -> 
    done() 

test_something.coffee

require './spec_helper' 
+0

क्या आप थोड़ा सा समझा सकते हैं, क्या हो रहा है? – Gobliins

64

परीक्षण फ़ोल्डर की जड़ में, एक वैश्विक परीक्षण सहायक test/helper.js जो अपने से पहले है बना सकते हैं और beforeEach

// globals 
global.assert = require('assert'); 

// setup 
before(); 
beforeEach(); 

// teardown 
after(); 
afterEach(); 
+8

आपको इसे स्पष्ट रूप से आवश्यकता नहीं होनी चाहिए। वास्तव में, यह एक त्रुटि फेंक देगा क्योंकि पहले, पहले, इत्यादि आवश्यक संदर्भ में मौजूद नहीं होंगे। जब तक यह परीक्षण निर्देशिका में शामिल है, कोड किसी भी परीक्षण से पहले निष्पादित किया जाना चाहिए। – khoomeister

+1

धन्यवाद @khoomeister जो पुराने संस्करण के लिए था! – AJcodez

+1

अपडेट किया गया मैं इसका बहुत अच्छा उपयोग करता हूं, लेकिन मुझे आश्चर्य है कि इस पर दस्तावेज़ कहां खोजें? – Zlatko

-1

मॉड्यूल का उपयोग वैश्विक सेटअप/टियरडाउन के लिए आसान बना सकता है आपका परीक्षण सूट यहाँ RequireJS का उपयोग कर एक उदाहरण (एएमडी मॉड्यूल) है:

पहले, आइए हमारे वैश्विक सेटअप/टियरडाउन के साथ एक परीक्षण पर्यावरण को परिभाषित करते हैं:

// test-env.js 

define('test-env', [], function() { 
    // One can store globals, which will be available within the 
    // whole test suite. 
    var my_global = true; 

    before(function() { 
    // global setup 
    }); 
    return after(function() { 
    // global teardown 
    }); 
}); 

हमारे जे एस धावक में (मोचा के एचटीएमएल धावक में शामिल है, अन्य के साथ libs और परीक्षण फ़ाइलें, एक <script type="text/javascript">…</script>, या बेहतर, एक बाहरी जे एस फ़ाइल के रूप में) के रूप में:

require([ 
      // this is the important thing: require the test-env dependency first 
      'test-env', 

      // then, require the specs 
      'some-test-file' 
     ], function() { 

    mocha.run(); 
}); 

some-test-file.js इस तरह लागू किया जा सकता:

// some-test-file.js 

define(['unit-under-test'], function(UnitUnderTest) { 
    return describe('Some unit under test', function() { 
    before(function() { 
     // locally "global" setup 
    }); 

    beforeEach(function() { 
    }); 

    afterEach(function() { 
    }); 

    after(function() { 
     // locally "global" teardown 
    }); 

    it('exists', function() { 
     // let's specify the unit under test 
    }); 
    }); 
}); 
संबंधित मुद्दे