Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在规范中使用require-grunt+;因果报应+;结茉莉_Javascript_Node.js_Gruntjs_Jasmine_Karma Runner - Fatal编程技术网

Javascript 如何在规范中使用require-grunt+;因果报应+;结茉莉

Javascript 如何在规范中使用require-grunt+;因果报应+;结茉莉,javascript,node.js,gruntjs,jasmine,karma-runner,Javascript,Node.js,Gruntjs,Jasmine,Karma Runner,模糊版本问题: 如何在规范中使用require和grunt 上下文: 我正在做一个现有的节点项目,还没有测试,所以我读了一些,并意识到要使用karma和jasmine 我读了一些短裙(包括这些): 因此,我尝试使用grunt运行我的规范,并得到以下错误: X遇到声明异常 ReferenceError:在文件:///(…)-spec.js(第2行)(1)中找不到变量:require 这句话是这样的: var myHelper = require(...); 但如果我使用终端“节点茉莉

模糊版本问题:

  • 如何在规范中使用require和grunt
上下文:

我正在做一个现有的节点项目,还没有测试,所以我读了一些,并意识到要使用karma和jasmine

我读了一些短裙(包括这些):

因此,我尝试使用grunt运行我的规范,并得到以下错误:

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

这句话是这样的:

var myHelper = require(...);
但如果我使用终端“节点茉莉花测试”,它就像一个魅力

我的项目结构:

  • 控制器/
  • 助手/
  • 模型/
  • 节点单元/
  • 资源/
  • 试验/
  • 测试/规格/
  • 观点/
  • app.js
  • Grunfile.js
  • package.json
在我的规范(insidetest/spec/)中,我使用require('../../helpers/helper.js'),这对于节点jasmine是可以的,但对于grunt则不行

节点茉莉花试验:

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

咕噜声:

通过运行“jasmine:pivotal”(jasmine)任务测试jasmine规范 幻影

ReferenceError:在处找不到变量:require app.js:1 Service Helper测试X遇到声明异常 ReferenceError:在文件:///(…)/test/spec/serviceheloper-spec.js中找不到变量:require (第2行)(1)

0.005s中有1个规格

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

由于警告而中止

我已将所有包安装到节点_模块中(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');
}
谢谢您的关注。

怎么办 这取决于:

  • 如果您有一些应用程序代码需要针对浏览器进行测试(例如,
    Angular
    Backbone
    ,等等),请使用
    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);
    
  • 如果您不需要在浏览器上运行测试(即严格测试
    NodeJS
    code),您可以通过删除
    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一样,变量上下文由包含在其中的闭包定义

    • Jasmine
      二进制文件在内部使用了
      NodeJS
      ,这使得
      require
      函数在节点应用程序的上下文中可用

    • Karma
      运行程序的作用相当于将
      标记写入浏览器,然后浏览器将相应的文件加载到
      PhantomJs
      中。因此,您的javascript上下文是全局的,您的文件只能访问全局上下文。在浏览器中,全局上下文由附加到
      窗口
      对象的所有内容定义,而
      窗口.require
      本身并不存在


    我不知道这些方法是否有帮助。。。