ReferenceError:未定义浏览器 - 使用Karma和Jasmine

时间:2017-03-08 15:16:50

标签: javascript node.js express jasmine karma-jasmine

在尝试使用Jasmine和Karma设置一些基本测试时,我得到ReferenceError: browser is not defined

这是我的Karma配置文件

// Karma configuration
// Generated on Wed Mar 08 2017 13:29:09 GMT+0000 (GMT)

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: [
        './spec/**/*.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 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,

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

然后我在这里显示了一个名为loginSpec.js的测试文件:

describe('login page', function() {

    beforeEach(function(){
        browser().navigateTo('/');
    });

    it('should have the correct title', function() {
        expect(browser.getTitle()).toEqual('Title');

    });
});

每当我在Karma工具窗口中运行测试时,我都会收到以下错误:

ReferenceError: browser is not defined
    at Object.<anonymous> (spec/loginSpec.js:11:9)
ReferenceError: browser is not defined
    at Object.<anonymous> (spec/loginSpec.js:15:16)

我不明白为什么浏览器突然没有定义,因为我在设置Karma之前进行了测试(使用WebdriverIO和selenium-standalone)。这些测试以相同的方式编写,没有关于browser

的错误

我也研究过并发现很多其他人都遇到过同样的问题,但是他们因为Angular的问题而得到了它,我没有使用它?

1 个答案:

答案 0 :(得分:0)

使用karma,jasmine没有可用的browser处理程序/对象,如WebdriverIO和selenium-standalone。

如果您希望使用jasmine编写单元测试用例来测试路径,可以通过注入$location角度服务来完成,如下所示:

describe('login page', function() {

    beforeEach(angular.mock.inject((_$rootScope_, _$location_) => {
       _$location_.path('/');
       _$rootScope_.$digest();
    }));

    it('should have the correct title', function() {
        expect(browser.getTitle()).toEqual('Title');

    });
});