我正在使用 Mocha 的混合版本,ti-mocha ,为基于 Titanium SDK 的应用程序构建单元测试。我对 BDD 和 mocha 完全陌生,所以 API 的学习曲线相当陡峭。这是我对精简测试工具的问题。我可以访问 index.js 模块、它的方法和属性。但是,我不知道如何访问该模块内的命名函数,在本例中为 doClick()。
我正在使用 mocha + Should.js。在下面的测试工具中,上下文“index”通过,但上下文“doClick”失败。我对这个 API 很陌生,我不确定我是否正确地提出了这个问题。如何访问模块内的功能?
index-mocha.js
// creates the "mocha" global necessary to run a test suite anywhere in your app
var should = require('should');
module.exports = function(index) {
// create the test suite
describe('mochatest', function() {
context('index', function() {
it('index exists', function() {
should.exist(index);
});
it('index.open function', function() {
should(index.open).be.a.Function;
});
it('id = index', function() {
index.id.should.equal('index');
});
});
context('doClick', function() {
it('doClick exists', function() {
should.exist(index.doClick);
// return;
});
it('doClick is a function', function() {
should(index.doClick).be.a.Function;
});
});
});
var outputFile = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, 'results.json');
outputFile.createFile();
mocha.setup({
reporter: 'ti-spec', // the reporter to use with your tests
outputFile: outputFile, // write results to the given Ti.Filesystem.File file
quiet: false // if true, suppress all console logging
});
// run the tests
mocha.run();
};
index.js
function doClick(e) {
alert($.label.text);
}
if(runTests){
require('ti-mocha');
$.index.addEventListener('open', function(){
require('index-mocha')($.index);
});
}
$.index.open();
最佳答案
很高兴看到有人在 Titanium 中进行测试:)
为了澄清一件事,变量 $
指的是当前 Controller 的实例。此外,Alloy 为您提供了对已通过此变量定义 id 的 View 元素的引用;这可能被视为一个小糖,因为所有这些 View 都可以通过 $.getViews()
访问。
因此, Controller 文件中定义的所有函数只能从该 Controller 内部访问。如果您希望从外部访问它们,最简单、最干净的方法就是导出它们。
这可以通过两种方式完成:
直接将它们添加到 Controller 对象
$.doClick = doClick;
通过使用
exports
变量exports.doClick = doClick;
结果将与编译期间完全相同,Alloy 会将 exports
变量(最初只是一个空对象)与您的 Controller 合并又名 $
。
然后,只需通过 require
而不是 index
View 传递 Controller ,即可访问 View 和新添加的监听器。
关于javascript - Mocha - 使用 ti-mocha 访问命名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650921/