Việc sử dụng mô-đun có thể giúp việc thiết lập/rách toàn cầu dễ dàng hơn bộ thử nghiệm của bạn. Dưới đây là một ví dụ sử dụng RequireJS (module AMD):
Đầu tiên, hãy định nghĩa một môi trường thử nghiệm với việc thiết lập toàn cầu của chúng tôi/teardown:
// 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
});
});
Trong Á hậu JS của chúng tôi (bao gồm trong Á hậu HTML mocha, cùng người kia libs và các tập tin kiểm tra, như một <script type="text/javascript">…</script>
, hoặc tốt hơn, như là một tập tin JS bên ngoài):
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
thể được thực hiện như thế này:
// 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
});
});
});
bạn có thể giải thích một chút, điều gì đang xảy ra ở đó không? – Gobliins