【发布时间】:2016-02-26 16:24:17
【问题描述】:
我正在尝试在 Karma/Jasmine 中为我项目中的特定模块编写一些单元测试,destination-filters。
模块声明:
angular.module('destination-filter', ['ngSanitize']);
除非我将 ngSanitize 作为依赖项删除,否则我的测试将失败。据我了解,这是因为当模块被实例化时,它会尝试引入该依赖项,但因为在我的 spec.js 文件中我没有声明该模块失败。
规格文件:
describe('Destination Filter Controller', function () {
// Set the variables
var $controller;
var mockNgSanitize;
beforeEach(module('destination-filter'));
beforeEach(function() {
module(function($provide) {
$provide.value('ngSanitize', mockNgSanitize);
});
});
beforeEach(inject(function (_$controller_) {
$controller = _$controller_('DestinationFilterController');
}));
it('should expect the controller to not be null', function() {
// Check the controller is set
expect($controller).not.toBeNull();
});
});
以前,在模拟服务或函数时,$provide 方法已被证明非常有用,但我不确定我在这里的使用是否正确。我假设以这种方式使用的$provide 不能模拟整个模块,而是模拟服务?
为了澄清,如果我从我的模块减速中删除 ...['ngSantize'])...,测试会正确实例化。我收到的错误是Error: [$injector:modulerr] destination-filter
【问题讨论】:
-
你的业力配置是否加载
angular-sanitize.js文件? -
它没有。我有点害怕开始在其中添加单独的文件。我知道这就是它的用途,但我真的不想开始在其中放置大量文件。除非您认为这样做可能足够公平。这是标准做法吗?
-
您需要在代码中包含您使用的 JS 文件,这样才能运行测试。这只是一个角度依赖。我不明白为什么不将它包含在测试中。
-
是的,成功了,干杯。
-
@yarons,你拯救了我的一天
标签: angularjs unit-testing mocking karma-jasmine