3

我想使用 jasmine 为 Sencha Touch 2 应用程序设置适当的测试环境。

我将本教程的前三个部分用于我的第一步:

我的实际问题如下:我的两个类(一个商店和一个视图)的两个配置条目需要分别调用我的主应用程序对象的方法/读取属性 Ext.Viewport 对象。

具体的:

1.)我的一家商店在我的应用程序的主命名空间(MyAppName.app.backendUrl)上读取了一个值

Ext.define('MyAppName.store.MyStore', {
    extend: 'Ext.data.Store',

    config: {
        model: 'MyAppName.model.MyModel',

        proxy: {
            type: 'ajax',
            url: MyAppName.app.backendUrl + '/data.json',
            reader: 'json'
        },

        autoLoad: true
    }
});

2.) 我的一个观点确实在 Ext.Viewport 上调用了一个方法 (Ext.Viewport.getOrientation()):

Ext.define('MyAppName.view.LoginView', {
    extend: 'Ext.form.Panel',
    alias: "widget.loginview",
    config: {
        title: 'Login',
        items: [
            {
                xtype: 'image',
                src: Ext.Viewport.getOrientation() == 'portrait' ? '../../../img/login.png' : '../../../img/login-small.png',
                style: Ext.Viewport.getOrientation() == 'portrait' ? 'width:80px;height:80px;margin:auto' : 'width:40px;height:40px;margin:auto'
            }
        ]
    }
});

不幸的是,这会崩溃,因为在进行这些调用时,尚未定义两个对象(MyAppName 和 Ext.Viewport)。这仅适用于测试设置(如教程所述,有一个特定的 app.js 仅用于测试)。当我在浏览器中运行实际应用程序时(通过“普通”app.js),不会发生此问题。

如何解决这个问题(所以:如何确保我的视图/存储文件在 MyAppname.app 和 Ext.Viewport 已经存在之后运行)?

非常感谢。

4

3 回答 3

2

我发现运行通常会打开您在单元测试Ext.application期间通常不需要的视图- 否则您会冒险进行集成测试,因此我避免使用 Sencha 开发加载程序。相反,我使用 Karma 来加载单元测试和应用程序类文件。您在文件中配置这些文件(下面的示例)。karma.conf.js

我改编了来自 Pivotal Labs 的优秀单元测试教程中的示例。由于 Karma 有一个内置的 Web 服务器,因此您不需要 Rails、Rake 或 pow,正如他们的第一个教程所述。使用 Karma 意味着您可以轻松地将单元测试与 IntelliJ IDEA 或 WebStorm 等 Javascript 工具以及https://saucelabs.com/等 CI 系统和云测试集成。您还可以将其配置为监视您的代码文件并在更新它们时自动重新运行单元测试。您还可以使用它karma-istanbul来执行代码覆盖率分析。

使用我在这里学到的技巧,我运行了一个setup.js在我的文件中配置的karma.conf.js文件,以便在单元测试之前加载。它创建了一个虚假的应用程序对象,以便控制器可以将自己分配给应用程序实例,并且它故意没有launch()方法。它还包括来自 Pivotal Labs 示例的 SpecHelper.js 代码。

// Create (but don't launch) the app
Ext.application({name: 'MyAppName' });

对于视图单元测试问题,您可以创建一个伪造的Ext.Viewport对象并添加一个 spyOn().andReturn() 来伪造Ext.Viewport.getOrientation()测试期间视图所需的方法。这意味着您的单元测试可以轻松涵盖两种方向情况。您还可以renderTo:在测试期间添加一个属性来检查呈现的视图:

describe("when portrait orientation", function() {
   var view;
   beforeEach(function () {
     if (!Ext.Viewport) Ext.Viewport = {};      
     spyOn(Ext.Viewport, 'getOrientation').andReturn('portrait');
     view = Ext.create('MyAppName.view.LoginView', {
         renderTo: 'jasmine_content'
     }
   }

   it("should render large image", function() { 
      expect(Ext.DomQuery.select('...')).toContain('img/login.png');
   });

   it("should render 80px style", function() {
      expect(Ext.DomQuery.select('...')).toContain('80px');
   });        
});

查看单元测试(解释如何使用该renderTo属性)。

我的setup.js文件如下所示,包括SpecHelper.js此处显示的代码。您需要这个才能使用该renderTo 属性。

控制器单元测试涵盖了如何将控制器连接到您的假应用程序实例。

setup.js这段代码从这里 窃取了一个 Karma 加载技巧,但与他们的示例不同,它避免使用开发加载程序。

Ext.Loader.setConfig({
    enabled: true,                  // Turn on Ext.Loader
    disableCaching: false           // Turn OFF cache BUSTING
});

// 'base' is set by Karma to be __dirname of karm.conf.js file
Ext.Loader.setPath({
    'Ext':  'base/touch/src',
    'MyAppName':   'base/app'
});

// Create (but don't launch) the app
Ext.application({name: 'MyAppName' });

Ext.require('Ext.data.Model');
afterEach(function () {
    Ext.data.Model.cache = {};      // Clear any cached models
});

var domEl;
beforeEach(function () {            // Reset the div with a new one.
    domEl = document.createElement('div');
    domEl.setAttribute('id', 'jasmine_content');
    var oldEl = document.getElementById('jasmine_content');
    if (oldEl) oldEl.parentNode.replaceChild(domEl, oldEl);
});

afterEach(function () {             // Make the test runner look pretty
    domEl.setAttribute('style', 'display:none;');
});

// Karma normally starts the tests right after all files specified in 'karma.config.js' have been loaded
// We only want the tests to start after Sencha Touch/ExtJS has bootstrapped the application.
// 1. We temporary override the '__karma__.loaded' function
// 2. When Ext is ready we call the '__karma__.loaded' function manually
var karmaLoadedFunction = window.__karma__.loaded;
window.__karma__.loaded = function () {};

Ext.onReady( function () {
    console.info("Starting Tests ...");
    window.__karma__.loaded = karmaLoadedFunction;
    window.__karma__.loaded();
});

业力.conf.js

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // Don't use Sencha Touch dynamic loading
        files: [
            'touch/sencha-touch-all-debug.js',
            'spec/Setup.js',      // Load stubbed app - does not call app.launch()
            { pattern: 'spec/**/*.js',          watched: true,  served: true, included: true },
            { pattern: 'app/**/*.js',           watched: true,  served: true, included: false},
            // Some class are not loaded by sencha-touch-all-debug.js
            // this tell Karma web server that it's ok to serve them.
            { pattern: 'touch/src/**/*.*',      watched: false, served: true, included: false}
        ],

//        // Use Sencha Touch static 'testing' app.js
//        files: [
//            './build/testing/PT/app.js',
//            './spec/SetUp.js',
//            './spec/**/*.js'
//        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE/.LOG_ERROR/.LOG_WARN/.LOG_INFO/.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera (has to be installed with `npm install karma-opera-launcher`)
        // - Safari (only Mac; has to be installed with `npm install
        // karma-safari-launcher`)
        // - PhantomJS
        // - IE (only Windows; has to be installed with `npm install
        // karma-ie-launcher`)
        //browsers: [ 'PhantomJS' ],
        browsers: ['Chrome'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    });
};
于 2014-09-29T00:59:42.073 回答
1

您需要以正确的顺序指定您需要的文件:spec/javascripts/support/jasmime.yml:

src_files:
    - touch/sencha-touch-all-debug.js   # Load Sencha library
    - spec/app.js                   # Load our spec Ext.Application
    - app/util/Urls.js #custom dependency
    - app/**/*.js                   # Load source files
于 2013-08-02T18:38:37.043 回答
0

解决该问题的一种方法是从initComponent. 这样它在实例化之前不会被调用,而不是在启动时。

Ext.define('MyAppName.view.LoginView', {
    extend: 'Ext.form.Panel',
    alias: "widget.loginview",
    config: {
        title: 'Login'
    },

    initComponent: function() {
        this.items = [
            {
                xtype: 'image',
                src: Ext.Viewport.getOrientation() == 'portrait' ? '../../../img/login.png' : '../../../img/login-small.png',
                style: Ext.Viewport.getOrientation() == 'portrait' ? 'width:80px;height:80px;margin:auto' : 'width:40px;height:40px;margin:auto'
            }
        ];
        this.callParent();

    }
});

商店也是如此,但在构造函数中

Ext.define('MyAppName.store.MyStore', {
    extend: 'Ext.data.Store',

    config: {
        model: 'MyAppName.model.MyModel',

        autoLoad: true
    },

    constructor: function(cfg) {
        this.proxy = {
            type: 'ajax',
            url: MyAppName.app.backendUrl + '/data.json',
            reader: 'json'
        };
        this.callParent(arguments)
    }
});
于 2014-10-12T02:47:01.310 回答