业力和茉莉:无法找到变量:require

时间:2016-11-08 04:25:20

标签: karma-runner karma-jasmine

这是我第一次尝试对某些代码进行单元测试,并且在使用Karma和Jasmine时出现此错误:

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
ReferenceError: Can't find variable: require
at unit/tests.js:1

我尝试npm install karma-browserify --save-dev,但这并没有解决问题。

知道怎么排序吗?

我的Karma conf文件:

// Karma configuration
// Generated on Tue Nov 08 2016 03:14:50 GMT+0000 (GMT 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'],


// list of files / patterns to load in the browser
files: [
   // '../shopping-basket.js',
    'unit/*.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/**/*.js': ['browserify']
},


// 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: ['PhantomJS'],
//browsers: ['Chrome'],


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

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
 })
}

tests.js

var myCode = require('./shopping-basket-functions');

describe('tests', function(){
    describe('testFunction', function(){
        it('should return 1', function(){
            // Call the exported function from the module
            myCode.testFunction().should.equal(1);
        })
    })
})

购物篮-functions.js

function testFunction () {
    return 1;
}

// If we're running under Node, 
if(typeof exports !== 'undefined') {
    exports.testFunction = testFunction;
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用此处的模板:https://www.npmjs.com/package/grunt-template-jasmine-nml中指定的answer

长话短说,它的作用是允许您使用NodeJS使用的CommonJS语法来引用和引入其他模块。请参阅下面的示例,了解如何在jasmine配置文件中引用它(同样,根据其他用户的回答):

jasmine: {
    options: {
        template: require('grunt-template-jasmine-nml'),
        helpers: 'spec/helpers/**/*.js',
        specs: 'spec/**/*.spec.js'
    }
}

答案 1 :(得分:0)

有同样的问题试图构建一个应用程序,phanotmjs继续爬行未定义的变量需求,通过以下方式解决: npm install grunt-template-jasmine-nml --save-dev

这将更新正确的模板,之后可以使用。 试: grunt测试-dd完成没有错误