1

我的测试设置有问题。当一个文件中的所有内容都可以工作时,它不会在代码分散在多个文件中时使用。AngularJS - 使用模块approuch进行测试

当代码传播按下面,我得到一个错误Error: [$injector:unpr] Unknown provider: twoPlusTwoFilterProvider <- twoPlusTwoFilter

// js/index.js 
angular.module('app', []); 

// js/twoPlusTwoFilter.js 
angular.module('app').filter('hex', function hex(){ 
    return function(input){ 
     return input+input; 
    } 
}); 

// here is my test 
describe('check sanity', function() { 

    beforeEach(module('app')); 

    it('should return 4', inject(function(hexFilter) { 
     expect(hexFilter(2)).toEqual(4); 
    })); 

}); 

仅供参考,我包括善缘的conf角嘲笑。任何建议非常感谢。

+0

您是否加载了karma.conf.js中的所有文件? – marneborn 2014-08-28 16:40:44

+0

什么是'twoPlusTwoFilter'? – PSL 2014-08-28 16:42:44

+0

@marneborn - 是的,所有图书馆,来源和测试.. – Iladarsda 2014-08-28 16:43:30

回答

1

您应该尝试注入filterprovider并获得hex过滤器。

var $filter; 

beforeEach(function() { 
    module('app'); 
}); 

beforeEach(inject(function (_$filter_) { //<-- Get the filter provider 
    $filter = _$filter_; 
})); 

it('should return 4', function() { 
    expect($filter('hex')(2)).toEqual(4); //Not get your `hex` filter and run it 
}); 

或注入过滤器前缀。

beforeEach(inject(function (_hexFilter_) { 
    $filter = _hexFilter_; 
})); 

Plnkr

过滤器是只将变换输入到输出的功能。但是过滤器需要依赖注入。为了达到这个目的,一个过滤器定义由一个工厂函数组成,该工厂函数用依赖注释并负责创建一个过滤函数。

+0

是我的内联'inject(function(filterNameHere){})'不够好? – Iladarsda 2014-08-28 16:44:48

+0

所有作品,谢谢!请告诉我们更多关于filterProvider&inject – Iladarsda 2014-08-28 16:48:52

+1

@Iladarsda我已经提供了官方文档链接以及答案中的摘录... – PSL 2014-08-28 16:49:55