javascript - Mocha - 使用 ti-mocha 访问命名函数

标签 javascript unit-testing titanium mocha.js

我正在使用 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/

相关文章:

javascript - Titanium:显示自定义对象 - 变量未定义

android - 通过公司代理的 Titanium Appcelerator

javascript - 带有此关键字的 requestAnimationFrame

javascript - 无法使用 removeChild 从 html 正文中删除元素

java - 在 JUnit 中继承一个类 - 这是一个很好的做法吗?

java - 坑突变 - if ( x !=null ) return null else throw new RuntimeException

javascript - appcelerator钛工作室未启动

javascript - 为什么我的 3d 立方体没有按预期旋转?

javascript - 在没有jQuery的情况下获取<a>标签的href属性值

unit-testing - 如何使用 f# 编写带有模拟的测试