KarmaJS,Jasmine,RequireJS等:如何使用需要测试模块 [英] KarmaJS, Jasmine, RequireJS, etc: How to Use Require for Testing Modules

查看:77
本文介绍了KarmaJS,Jasmine,RequireJS等:如何使用需要测试模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently, I have an exercise project up for getting comfortable with KarmaJS -- and Unit Testing, at large. The broad issue is that I really have no transparent view of what Karma is doing behind the scenes, and I can't seem to find adequate documentation in relevant areas. Without further delay...

这是我的文件夹结构

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.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
  });
};

test-main.js

test-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
});

test-test-file.js

test-test-file.js

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

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

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

});

test-file.js

test-file.js

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

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

        return {
            some: 'module'
        };
    };

});






问题&描述

我希望听到答案的关键点是

Key points I would love to hear answers for are


  • {pattern:'...', include:true | false }做什么?

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

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

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

  • test-main.js实际上做了什么;这是为了什么?

  • what does { pattern: '...', include: true|false } do?
  • best way to exclude all the extra stuff inside the bower directories.
  • what files do I need to include in the test-main.js file?
  • what files do I need to include in the karma.conf.js file?
  • what does test-main.js actually do; what's it for?

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

The times I receive errors & issues is as soon as I wrap my spec in a define(...) call -- event when I give the module an ID -- define('someId', function(){ ... }) -- do I need to return something out of this module, as it is a define call?

其他时候,我收到'ol 错误:'/ base / src /没有时间戳app.js!的。 时间戳,当然!我多么愚蠢...... - 这对世界来说意味着什么?!有时我会得到臭名昭着的 0 0执行错误 - 我也可以在这里使用一些清晰度。真的,我得到了很多错误:'...没有时间戳......'错误 - 甚至 404 s 似乎我应该使用karma.conf.js 文件 config ... ???

Other times, I receive the 'ol ERROR: 'There is no timestamp for /base/src/app.js!'. "Timestamp, of course! How silly of me..." -- what in the world does this mean?! Sometimes I get the infamous "Executed 0 of 0 ERROR" -- I could also use some clarity here, please. Really, I get plenty of ERROR: '...no timestamp...' errors -- and even 404s when it seems I should be pulling that library in with the karma.conf.js files config...???

甚至看起来通常当我明确告诉业力排除 src / app.js 我仍然得到 404 s和错误。

It even seems that usually when I explicitly tell karma to excludesrc/app.js I still get 404s and errors.

tl; dr

显然,我关于Karma和* DD的新手有点混淆...

Obviously, I'm a bit of a confused novice about Karma and *DD at large...

我可以运行 test-test-file.js 当我的karma.conf.js 文件数组看起来像 ['test-main.js','test / spec / test-test-file.js'] - 但是,如果我将我的测试包装在RequireJS定义调用中,我会得到不匹配的匿名定义()错误如上所述。

I can run test-test-file.js fine when my karma.conf.js files array looks like [ 'test-main.js', 'test/spec/test-test-file.js' ] -- but, still, if I wrap my test in a RequireJS define call I get the "Mismatching anonymous define()" error mentioned above.

似乎当我添加 {pattern:'...'时,包括: false } 然后业力只是没有添加任何我的文件给定拍无论如何(???)。

It seems that when I add { pattern: '...', include: false } then karma just doesn't add any of my files for the given pattern whatsoever (???).

如果有人甚至可以简单地指导我如何使用RequireJS和Karma - 也就是说我可以将我的测试包裹在一个定义/要求调用并拉入我要测试的模块...非常感谢。

If someone can even simply direct me toward how to use RequireJS with Karma -- namely so that I can just wrap my tests in a define/require call and pull in the module I want to test... That would be greatly appreciated.

因为它有点难以保持这些类型的问题简短并且仍然提供了足够的信息,我希望我没有提供足够的信息。

As its somewhat difficult to keep these types of questions short and still provide adequate information, I hope I didn't make it too long.

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

After reading the answer from glepretre and some fiddling on my own, I reconfigured my project as follows:


  • test-main.js 移至 test / test-main.js

  • test-test-file.js 重命名为 testFileSpec.js - 将其从 test / spec test /

  • Moved test-main.js to test/test-main.js,
  • renamed test-test-file.js to testFileSpec.js -- moved it from test/spec to test/,

karma.conf.js:

karma.conf.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'

],
....

test / test-main.js:

/* **************** HOW COME THE DEFAULT (Karma-generated) CONFIGURATION DOES ***NOT WORK???
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));
    }
});
*/

var tests = [];
for (var file in window.__karma__.files) {
    if (/Spec\.js$/.test(file)) {
        tests.push(file);
    }
}

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

    paths: {},
    shim: {},

    // dynamically load all test files
    //deps: allTestFiles,
    //
    deps: tests,

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

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

I am now running Unit Tests successfully! Special Thanks to glepretre & all other contributors.

感谢您的任何见解:)

推荐答案

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

OK, I will try to address each question at a time:

问题1



  • {pattern:'...', included:true | false }吗?

  • what does { pattern: '...', included: true|false } do?

Karma的默认行为是:

Karma's default behavior is to:


  • 查找与 模式 匹配的所有文件(必填)属性)

  • 观察他们的更改( 观看 选项)以重新启动单元测试编辑代码时的结果(如果只保留默认 autoWatch 默认值 true )。

  • 使用自己的网络服务器提供服务( 服务 选项)

  • 使用<$ c将它们包含在浏览器中$ c>< script> ( 包含 选项)

  • find all files matching the pattern (mandatory property)
  • watch them for changes (watched option) in order to restart your unit tests to give you live result when you are editing your code (works if only you leave the default autoWatch default value to true).
  • serve them using its own webserver (served option)
  • include them in the browser using <script> (included option)

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

So, in the files array of the karma config you can use default behavior by adding only string patterns:

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

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

Or use the full object syntax to customize each option:

files: [
  {pattern: 'src/**/*.js', watched: true, served: true, included: false}
]

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

Using requireJS, you DO NOT want them to be included because it will be in conflict with requireJS behavior!


包含。说明:文件是否应使用< script> 标记包含在浏览器中?如果要手动加载,请使用false,例如。使用 Require.js

Included. Description: Should the files be included in the browser using <script> tag? Use false if you want to load them manually, eg. using Require.js.

来自 karma / config / files docs

注意:注意你的订单添加数组中的文件/模式。这很重要!要了解更多信息,请在您的业力配置中设置 logLevel:config.LOG_DEBUG

问题2



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

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

At least all required files for the proper functioning of your components for unit testing.

基本上,中定义的所有文件定义([]) require() blocks。

Basically, all files listed in your define([]) and require() blocks.

问题3



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

你准备做什么?

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

Based on what I wrote before, you can see that you can add selectively the files you will need in your tests.

我用来添加模式'/ bower_components / ** / * .js'甚至/亭子_components / ** / * .html'当我的bower包使用模板时。我从未注意到任何重大的性能问题如果你担心的是......你可以定义你需要的文件模式。

I use to add the pattern '/bower_components/**/*.js' and even '/bower_components/**/*.html' when my bower packages are using templates. I never noticed any significant performance issue if that's what you are worried about... Up to you to define the file patterns you will need.

问题4& amp; ; 5



  • test-main.js实际上做了什么;这是为了什么?

  • what does test-main.js actually do; what's it for?

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

what files do I need to include in the test-main.js file?

test-main.js 文件的目的是查找和在启动Karma之前加载测试文件。它连接了Karma和requireJS之间的点。

The purpose of the test-main.js file is to find and load your test files before starting Karma. It connects the dots between Karma and requireJS

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

You must choose a convention to name your test files and then define the TEST_REGEXP to match all of them.

官方角度样式指南和应用结构的最佳做法建议使用后缀 * _ test.js

编辑:你的正则表达式无效,因为它被定义为捕获spec.js||最后的test.js或您的spec文件名以file.js结尾;)请参阅http://regex101.com/r/bE9tV9/1

Your regexp is not working because it is defined to catch "spec.js" || "test.js" at the end or your spec file name is ending by "file.js" ;) Please see http://regex101.com/r/bE9tV9/1

还有一件事

我希望我足够清楚。您可以使用Angular +查看我们项目的入门应用程序结构: angular-requirejs-ready 。它已经与Karma和Protractor一起设置和测试。

I hope I was clear enough. You can have a look at our starter app structure for our projects using Angular + Require: angular-requirejs-ready. It's already set up and tested with both Karma and Protractor.

这篇关于KarmaJS,Jasmine,RequireJS等:如何使用需要测试模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆