【问题标题】:How use require inside a spec - grunt + karma + jasmine in node如何在规范中使用 require - 节点中的 grunt + karma + jasmine
【发布时间】:2014-10-14 07:20:13
【问题描述】:

模糊版本问题:

  • 如何在带有 grunt 的规范中使用 require?

上下文:

我正在开发一个尚未测试的现有节点项目,所以我阅读了一些并意识到使用 karma 和 jasmine。

我读了一些教程(包括这些):

所以我尝试使用 grunt 运行我的规范并收到此错误:

X 遇到声明异常 ReferenceError:找不到变量:文件中的要求:///(...)-spec.js(第2行)(1)

这条线是这样的:

var myHelper = require(...);

但是如果我通过终端“node-jasmine test”使用它就像一个魅力......

我的项目结构:

  • 控制器/
  • 帮手/
  • 型号/
  • node_modules/
  • 资源/
  • 测试/
  • 测试/规范/
  • 观看次数/
  • app.js
  • Gruntfile.js
  • package.json

在我的规范中(在 test/spec/ 中),我使用了 require('../../helpers/helper.js'),这对于 node-jasmine 是可以的,但对于 grunt 则不行。

节点茉莉花测试:

.....

在 0.015 秒内完成 5 次测试,5 次断言,0 次失败,0 次跳过

咕噜声:

运行“jasmine:pivotal”(茉莉花)任务测试茉莉花规格通过 幻影JS

ReferenceError:找不到变量:需要在 app.js:1 Service Helper Tests X 遇到声明异常 ReferenceError:找不到变量:文件中的要求:///(...)/test/spec/serviceHelper-spec.js (第 2 行)(1)

0.005 秒内 1 个规范。

1 失败警告:任务“jasmine:pivotal”失败。使用 --force 继续。

由于警告而中止。

我已将所有包安装到 node_modules 中(package.json 中没有依赖项),我的 Gruntfile.js 是:

'use strict';

module.exports = function(grunt) {
    var $srcFiles = 'app.js';
    var $testFiles = 'test/spec/*-spec.js';
    var $outputDir = 'test/target'
    var $junitResults = $outputDir + '/junit-test-results.xml';
    var $jasmineSpecRunner = $outputDir + '/_SpecRunner.html';
    var $coverageOutputDir = $outputDir + '/coverage';


    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // Jasmine test
        jasmine: {
            pivotal: {
                src: $srcFiles,
                options: {
                    specs: $testFiles,
                    outfile: $jasmineSpecRunner,
                    keepRunner: 'true'  // keep SpecRunner/outfile file
                }
            }
        },

        // coverage using Karma
        karma: {
            continuous: {
                singleRun: 'true',
                browsers: [ 'PhantomJS' ]
            },

            options: {
                plugins: [
                    'karma-jasmine',
                    'karma-phantomjs-launcher',
                    'karma-junit-reporter',
                    'karma-coverage'
                ],
                frameworks: [ 'jasmine' ],
                files: [ $srcFiles, $testFiles ],
                reporters: [ 'junit', 'coverage' ],
                junitReporter: {
                  outputFile: $junitResults
                },
                preprocessors: {
                    // source files must be a literal string
                    'helpers/*.js': [ 'coverage' ]
                },
                coverageReporter: {
                    type: 'lcov',
                    dir: $coverageOutputDir
                }
            }
        },

        // export Karma coverage to SonarQube
        karma_sonar: {
            your_target: {
                // properties for SonarQube dashboard
                project: {
                    key: 'net.ahexample:ahexample-jasmine-karma-sonar',
                    name: 'Jasmine with Karma and SonarQube Example',
                    version: '0.0.1'
                }

                // sources property is set at runtime (see below)
            }
        },

        clean: [ $outputDir ]
    });


    /*
     * Task to set karma_sonar's sources property.
     * This is needed because karma (coverage) stores its results in a
     * directory whose name uses the browser's user agent info
     * (name/version and the platform name).
     * The latter may well he different to the OS name and so its needs an
     * OS to platform translator.
     * For example, OS name for Apple Mac OS X is Darwin.
     */
    grunt.registerTask('set-karma-sonar-sources-property', function() {
        var $done = this.async();
        var $phantomjs = require('karma-phantomjs-launcher/node_modules/phantomjs');
        var $spawn = require('child_process').spawn;
        var $phantomUserAgent = $spawn($phantomjs.path,
            // phantomjs script to print user agent string
            [ 'lib/phantomjs-useragent.js' ]
        );

        /*
         * Construct coverage LCOV file path from PhantomJS'
         * user agent string, then use it to set karma_sonar's
         * sources property.
         */
        $phantomUserAgent.stdout.on('data', function(msg) {
            var $useragent = require('karma/node_modules/useragent');
            var $agent = $useragent.parse(msg);
            // An example of dirName is 'PhantomJS 1.9.7 (Mac OS X)'
            var $dirName = $agent.toAgent() + ' (' + $agent.os + ')';
            var $coverageResults = $coverageOutputDir + '/' + $dirName + '/lcov.info';
            var $sonarSources = makeSonarSourceDirs($srcFiles, $coverageResults);
            var $karmaSonarConfig = 'karma_sonar';
            var $ksConfig = grunt.config($karmaSonarConfig);

            grunt.log.writeln('coverage LCOV file: ' + $coverageResults);
            $ksConfig['your_target']['sources'] = $sonarSources;
            grunt.config($karmaSonarConfig, $ksConfig);

        });

        $phantomUserAgent.on('close', function(exitCode) {
            $done();
        });


        /*
         * Create sonar source object for each directory of source file pattern.
         */
        function makeSonarSourceDirs($filesPattern, $coverageResults) {
            var $path = require('path');
            var $dirs = [];

            grunt.file.expand(
                {
                    filter: function($filePath) {
                        $dirs.push({
                            path: $path.dirname($filePath),
                            prefix: '.',    // path prefix in lcov.info
                            coverageReport: $coverageResults,
                            testReport: $junitResults
                        });
                    }
                },
                $filesPattern
            );

            return $dirs;
        }
    });


    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-karma-sonar');


    grunt.registerTask('test', [ 'jasmine', 'karma:continuous' ]);
    grunt.registerTask('sonar-only', [ 'set-karma-sonar-sources-property', 'karma_sonar' ]);
    grunt.registerTask('sonar', [ 'test', 'sonar-only' ]);
    grunt.registerTask('default', 'test');
}

感谢您的关注。

【问题讨论】:

标签: javascript node.js gruntjs jasmine karma-runner


【解决方案1】:

如何

这取决于:

  1. 如果您有一些应用程序代码需要针对浏览器进行测试(例如AngularBackbone 等) - 使用 Karma 而不要使用 require。然后确保在测试之前加载您的 helpers.js 文件。

    // @file Gruntfile.js
    // https://github.com/karma-runner/grunt-karma
    grunt.initConfig({        
      karma: {
        client: {
          options: {
            files: ['client/*.js', 'helpers/*.js', 'test/*.js']
          }
        }
      }
    });
    
    // @file helpers.js
    (function () {
      window.helpers = {
        foo: function () {
          return 'bar';
        }
      };
    })();
    
    // @file spec.js
    (function (helpers) {
    
      it('does the thing', function () {
        expect(helpers.foo()).toBe('bar');
      });
    
    })(window.helpers);
    
  2. 如果您不需要针对浏览器运行测试(即您正在严格测试 NodeJS 代码),您可以通过删除 Karma 并严格使用 Jasmine 来简化设置:

    // @file Gruntfile.js
    // https://github.com/gruntjs/grunt-contrib-jasmine
    grunt.initConfig({
      jasmine: {
        server: {
          src: 'server/*.js',
          options: {
            specs: 'test/*.js',
            helpers: 'helpers/*.js'
          }
        } 
      }
    });
    
    // @file helpers.js
    (function () {
      module.exports = {
        foo: function () {
          return 'bar';
        }
      };
    })();
    
    // @file spec.js
    (function () {
      var helpers = require('helpers'); // require is available
    
      it('does the thing', function () {
        expect(helpers.foo()).toBe('bar');
      });
    
    })();
    

为什么

require 不存在,因为您使用 Karma 运行测试。 Karma 只需在您选择的浏览器中加载文件并按照您在karma.conf.js 中提供的顺序执行它们。它在内部使用您提供的测试框架(在本例中为 Jasmine)对您提供的浏览器(在本例中为 PhantomJS)运行测试。

与所有 JavaScript 一样,变量 context 由包含在其中的闭包定义。

  • Jasmine 二进制文件在内部使用NodeJS,即emulates CommonJS require,使您可以在节点应用程序的上下文中使用require 函数。

  • Karma 运行器相当于将<script src="[path]"> 标记写入浏览器,然后每个浏览器将相应的文件加载到PhantomJs。因此,您的 javascript 上下文是全局的,您的文件只能访问全局上下文。在浏览器中,全局上下文由附加到 window 对象的所有内容定义,window.require 本身并不存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多