KarmaJS,Jasmine,RequireJS等:如何使用需要测试模块

时间:2014-11-20 21:46:55

标签: unit-testing requirejs jasmine karma-runner karma-jasmine

使用RequireJS运行Karma + Jasmine测试 - 开始

帮助! 。 。 。 _ _ _。 。 。 SOS!

目前,我有一个练习项目,以便对KarmaJS和单元测试感到满意。广泛的问题是我真的没有透视Karma在幕后所做的事情,而且我似乎无法在相关领域找到足够的文档。没有进一步的延迟...

以下是文件夹结构

root
    |-/lib
        |-/[dependencies] (/angular, /angular-mocks, /bootstrap, /etc)  # from bower
    |-/src                                                              
        |-/[unreferenced directories] (/js, /css, /views)               # not referenced anywhere
        |-app.js                                                        # sets up angular.module('app', ...)
        |-globals.js                                                    # may be referenced in RequireJS main file; not used.
        |-index.html                                                    # loads bootstrap.css and RequireJS main file
        |-main.js                                                       # .config + require(['app', 'etc'])
        |-routeMap.js                                                   # sets up a single route
        |-test-file.js                                                  # *** simple define(function(){ return {...}; })
    |-/test
        |-/spec
            |-test-test-file.js                                         # *** require || define(['test-file'])
    |-.bowerrc                                                          # { "directory": "lib" }
    |-bower.json                                                        # standard format
    |-karma.conf.js                                                     # *** HELP!
    |-test-main.js                                                      # *** Save Our Souls!!!

karma.conf.js

// Karma configuration
// Generated on Wed Nov 19 2014 15:16:56 GMT-0700 (Mountain Standard Time)

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', 'requirejs'],


    // list of files / patterns to load in the browser
    files: [
      //'test/spec/test-test-file.js',
      //'lib/**/*.js',
      //'src/**/*.js',
      //'test/spec/**/*.js',
      'test-main.js',
      {pattern: 'lib/**/*.js', included: false},
      {pattern: 'src/**/*.js', included: false},
      {pattern: 'test/spec/*.js', included: true}
    ],


    // list of files to exclude
    exclude: [
        'lib/**/!(angular|angular-mocks|angular-resource|angular-route|require|text).js',
        'lib/**/**/!(jquery|bootstrap).js',
        'src/app.js'
    ],


    // 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'
    // 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 || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.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
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

测试main.js

var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

var pathToModule = function(path) {
    return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};

Object.keys(window.__karma__.files).forEach(function(file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        allTestFiles.push(pathToModule(file));
    }
});

require.config({
    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base/src',

    paths: {

        angular: '../lib/angular/angular',
        ngRoute: '../lib/angular-route/angular-route',
        jquery: '../lib/jQuery/dist/jquery',
        bootstrap: '../lib/bootstrap/dist/js/bootstrap',
        models: 'models',
        controllers: 'controllers',
        globals: 'globals',
        routeMap: 'routeMap'
    },
    shim: {
        angular: {
            exports: 'angular'
        },
        ngRoute: {
            deps: ['angular']
        },
        jquery: {
            exports: '$'
        },
        bootstrap: {
            deps: ['jquery']
        }
    },

    // dynamically load all test files
    deps: allTestFiles,

    // we have to kickoff jasmine, as it is asynchronous
    callback: window.__karma__.start
});

测试试验file.js

console.log('....................');

define(function(){
    //console.log('testing test-file', testFile);

    describe('Testing testing', function(){
        it('should work', function(){
            expect(true).toEqual(true);
        });
    });

});

测试file.js

define('testFile', [], function(){

    return function init(sandbox){
        var app, application = app = sandbox.app
          , globals = sandbox.globals;

        return {
            some: 'module'
        };
    };

});

问题&描述

我很想听到答案的关键点是

  • {pattern:' ...', include:true | false }是做什么的?
  • 排除凉亭目录中所有额外内容的最佳方法。
  • 我需要在test-main.js文件中包含哪些文件?
  • 我需要在karma.conf.js文件中包含哪些文件?
  • test-main.js实际上做了什么;这是为了什么?

我收到错误的时间&问题是我在define(...)调用中包装我的规范时 - 当我给模块一个ID时发生事件 - define('someId', function(){ ... }) - 我是否需要从模块返回一些内容,因为它是define电话?

其他时候,我收到了' ol 错误:' / base / src / app.js没有时间戳!' 。 "时间戳,当然!我真傻......" - 这对世界来说意味着什么?!有时我会得到臭名昭着的" 执行0 0错误" - 我也可以在这里使用一些清晰度。真的,我得到了很多错误:' ...没有时间戳...' 错误 - 甚至{em>似乎404配置来推送那个库...... ???

通常,当我明确告诉业力排除files时,我仍然会得到src/app.js和错误。

TL;博士

显然,我对Karma和* DD有点困惑的新手...

当我的karma.conf.js 404数组看起来像test-test-file.js时,我可以运行files - 但是,如果我将我的测试包装在RequireJS定义调用中,我会得到" 不匹配的匿名定义()"上面提到的错误。

似乎当我添加 {pattern:' ...',include: false } 时,业力似乎没有添加任何给定模式的文件(???)。

如果有人甚至可以简单地指导我如何将RequireJS与Karma一起使用 - 也就是说我可以将我的测试包装在 define / require 调用中并拉入我要测试的模块......非常感谢。

由于有些难以将这些类型的问题保持简短并且仍能提供足够的信息,我希望我没有做太久。


修改

在阅读了glepretre的答案和我自己的一些小提琴后,我重新配置了我的项目如下:

  • [ 'test-main.js', 'test/spec/test-test-file.js' ]移至test-main.js
  • test-test-file.js 重命名为 testFileSpec.js - 将其从test/test-main.js移至test/spec

karma.conf.js:

test/

测试/测试main.js:

...
// list of files / patterns to load in the browser
files: [
    {pattern: 'lib/**/*.js', included: false},
    {pattern: 'src/**/*.js', included: false},
    {pattern: 'test/**/*Spec.js', included: false},

    'test/test-main.js'

],
....

我现在正在成功运行单元测试! 特别感谢glepretre&所有其他贡献者


感谢您的任何见解:)

1 个答案:

答案 0 :(得分:28)

好的,我会尝试一次解决每个问题:

问题1

  
      
  • {pattern:' ...',包括:true | false }是做什么的?
  •   

Karma的默认行为是:

  • 找到与 pattern (强制属性)
  • 匹配的所有文件
  • 观看更改( watched 选项)以重新启动单元测试,以便在编辑代码时为您提供实时结果(只有您保留默认值{{ 1}}默认值为autoWatch)。
  • 使用自己的网络服务器( true 选项)
  • 为他们提供服务
  • 使用served <script> 选项)将其包含在浏览器中

因此,在karma配置的included数组中,您可以通过仅添加字符串模式来使用默认行为:

files

或使用完整对象语法自定义每个选项:

files: [
  // this will match all your JS files 
  // in the src/ directory and subdirectories
  'src/**/*.js'
]

使用requireJS,你不希望它们被包括在内,因为它会与requireJS行为发生冲突!

  

<强>包括在内。说明:文件是否应使用files: [ {pattern: 'src/**/*.js', watched: true, served: true, included: false} ] 标记包含在浏览器中?如果要手动加载,请使用false,例如。使用 Require.js

来自karma/config/files docs

注意:请注意在数组中添加文件/模式的顺序。这很重要!要了解更多信息,请在您的业力配置中设置<script>

问题2

  
      
  • 我需要在karma.conf.js文件中包含哪些文件?
  •   

至少所有必需的文件,以便您的组件正常运行以进行单元测试。

基本上,logLevel: config.LOG_DEBUGdefine([])块中列出了所有文件。

问题3

  
      
  • 排除凉亭目录中所有额外内容的最佳方法。
  •   

你准备做什么?

根据我之前写的内容,您可以看到您可以有选择地添加测试中需要的文件。

当我的凉亭包使用模板时,我用来添加模式require()甚至'/bower_components/**/*.js'。我从未注意到任何重大的性能问题,如果您担心的是什么......由您来定义您需要的文件模式。

问题4&amp; 5

  
      
  • test-main.js实际上做了什么;它的用途是什么?

  •   
  • 我需要在test-main.js文件中包含哪些文件?

  •   

'/bower_components/**/*.html'文件的目的是在启动Karma之前查找并加载测试文件。它连接了Karma和requireJS之间的点。

您必须选择一个约定来命名您的测试文件,然后定义test-main.js以匹配所有这些文件。

&#34;官方&#34; angular style guide and best practices for app structure建议使用后缀TEST_REGEXP

编辑:您的正则表达式无法正常工作,因为它被定义为最后捕获*_test.js或您的规范文件名以"spec.js" || "test.js"结尾;)请参阅{{ 3}}

还有一件事

我希望我足够清楚。您可以使用Angular + Require http://regex101.com/r/bE9tV9/1查看我们的项目的入门应用程序结构。它已经与Karma和Protractor一起设置和测试。