【问题标题】:Jasmine unit test module is not definedJasmine 单元测试模块未定义
【发布时间】:2017-08-19 00:24:36
【问题描述】:

我目前正忙于对 Angular 进行 jasmine 单元测试。 我已将此单元测试放在 test.js 中

describe('The countInput filter', function(){
    var $filter;

    beforeEach(function(){
        module('countInputFilter');

        inject(function(_$filter_){
            $filter = _$filter_;
        });
    });

    it('Should not give an output when the length of the input is > 3', function(){

        var input = 'test';

        result = $filter('countInputFilter')(input);

        expect(result).toBe(null);
    });


});

当我使用 karma start karma.conf.js 运行它时,我收到错误:未定义模块。

在我的 karma.conf.js 文件中,我有以下文件代码:

files: [
  '../bower_components/angular/angular.js',
  '../bower_components/angular-mocks.js',
  '../bower_components/angular-route/angular-route.js',
  '../scripts/**/*.js',
  '../scripts/filters.js',
  'spec/**/*.js',
  'spec/*.js'
],

而我的项目结构是:

scripts
--filters.js
test
--spec
----test.js
--karma.conf.js

第一次尝试使用 Jasmine 进行单元测试,但我没有看到错误。

26 03 2017 11:29:10.103:WARN [watcher]:模式“C:/Users/user/Desktop/angular/bower_components/angular-mocks.js”不匹配任何文件。 26 03 2017 11:29:10.134:WARN [业力]:没有捕获的浏览器,打开 http://localhost:9876/ 26 03 2017 11:29:10.150:INFO [karma]: Karma v1.5.0 服务器开始于http://0.0.0.0:9876/ 2017 年 2 月 3 日 11:29:10.150:INFO [启动器]:以无限并发启动浏览器 Chrome 26 03 2017 11:29:10.181:INFO [启动器]: 启动浏览器 Chrome

【问题讨论】:

    标签: angularjs jasmine


    【解决方案1】:

    检查模块名称。

    模块名称和过滤器名称不能相同。

    module('countInputFilter');

    result = $filter('countInputFilter')(input);

    如果filter.js中的模块名称为countInput,过滤器名称为countInputFilter

    试试下面的代码:

    describe('The countInput filter', function(){
      var $filter;
    
      beforeEach(function(){
        module('countInput');
    
        inject(function(_$filter_){
            $filter = _$filter_;
        });
      });
    
      it('Should not give an output when the length of the input is > 3', function(){
    
        var input = 'test';
    
        result = $filter('countInputFilter')(input);
    
        expect(result).toBe(null);
      });
    
    
    });
    

    另外你filter.js应该是下面这样的:

    angular.module('countInput', [])
      .filter('countInputFilter', function () {
        return function (x) {
            ...
        };
    });
    

    您能否也分享您的filter.js 代码。

    Here is the sample jsfiddle link for unit testing filter

    【讨论】:

    • angular-mocks.js 警告现已修复并消失。我将模块中的名称替换为 countInput(过滤器的名称是 countInputFilter) 错误:[$injector:nomod] 模块 'countInput' 不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。
    • 检查更新的答案。也分享你的filter.js代码
    • 非常感谢!我修复了 angular-mocks.js 的路径和模块的名称。现在可以使用了
    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 2016-06-24
    • 2015-10-12
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    相关资源
    最近更新 更多