2012-05-12 20 views
46

Şimdi javascript birim testi için mocha kullanıyorum.Global `before` ve mocha için beforeEach?

Birden fazla sınama dosyam var, her dosyanın bir before ve beforeEach vardır, ancak tam olarak aynıdır.

Genel bir before ve beforeEach hepsini nasıl (veya bunlardan bazıları) sağlayabilirim?

cevap

26

before veya beforeEach'u ayrı bir dosyada (spec_helper.coffee kullanıyorum) belirtin ve gerekiyor.

spec_helper.coffee

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

Test klasörünün köküne olarak test_something.coffee

require './spec_helper' 
+0

Biraz açıklayabilir misiniz, orada neler oluyor? – Gobliins

64

, senin daha önce sahip küresel bir deney yardımcı test/helper.js oluşturup beforeEach

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

// setup 
before(); 
beforeEach(); 

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

Açıkça gerektirilmemelidir. Aslında, bir hata atacaktır, çünkü önce, BeforeEach, vb. Gerekli bağlamda bulunmayacaktır. Test dizinine dahil edildiği sürece, kod testlerden önce yapılmalıdır. – khoomeister

+1

teşekkürler eski bir sürüm için khoomeister oldu! updated – AJcodez

+1

Bunu çok güzel kullanıyorum, ama üzerinde dokümanları nerede bulacağımı merak ediyorum? – Zlatko

-1

Modüllerin kullanımı, global bir kurulum/göz atma işlemini daha kolay hale getirebilir Test takımın. İşte RequireJS kullanarak bir örnek (AMD modülleri) 'dir:

Öncelikle global kurulum/devrelerde bir test ortamı tanımlayalım: Bizim JS koşucu olarak

// 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 
    }); 
}); 

(diğer boyunca, mocha HTML koşucu dahil libs ve test dosyaları, bir <script type="text/javascript">…</script>, ya da daha iyi, gibi harici JS dosyası):

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 böyle uygulanabilir:

// 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 
    }); 
    }); 
}); 
İlgili konular