我花了很长时间来试图覆盖提供给模块配置函数的注入常量.我的代码看起来像
common.constant('I18n',); common.config(['I18n', function(I18n) { console.log("common I18n " + I18n) }]);
我们通常的方法是保证I18n在我们的单元测试中被注入了
module(function($provide) { $provide.constant('I18n',); });
这适用于我的控制器,但似乎配置功能不会查看$provide
模块外部的内容.它不是获取模拟值,而是将早期值定义为模块的一部分.(在我们的测试中未定义;在下面的plunker中,'foo'.)
下面是一个工作的plunker(看看控制台); 有谁知道我做错了什么?
http://plnkr.co/edit/utCuGmdRnFRUBKGqk2sD
我认为根本问题是您在配置块之前定义常量,因此每次加载模块时,将覆盖可能存在的任何模拟值.我的建议是将常量和配置分离成单独的模块.
首先:茉莉花似乎在你的傻瓜中不能正常工作.但我不太确定 - 也许其他人可以再次检查这个.不过我已经创建了一个新的plunkr(http://plnkr.co/edit/MkUjSLIyWbj5A2Vy6h61?p=preview)并按照这些说明操作:https://github.com/searls/jasmine-all.
您将看到您的beforeEach
代码永远不会运行.你可以检查一下:
module(function($provide) { console.log('you will never see this'); $provide.constant('I18n', { FOO: "bar"}); });
你需要两件事:
功能中的真正测试it
- expect(true).toBe(true)
足够好
您必须inject
在测试中的某处使用,否则module
将不会调用提供给的函数,并且不会设置常量.
如果您运行此代码,您将看到"绿色":
var common = angular.module('common', []); common.constant('I18n', 'foo'); common.config(['I18n', function(I18n) { console.log("common I18n " + I18n) }]); var app = angular.module('plunker', ['common']); app.config(['I18n', function(I18n) { console.log("plunker I18n " + I18n) }]); describe('tests', function() { beforeEach(module('common')); beforeEach(function() { module(function($provide) { console.log('change to bar'); $provide.constant('I18n', 'bar'); }); }); beforeEach(module('plunker')); it('anything looks great', inject(function($injector) { var i18n = $injector.get('I18n'); expect(i18n).toBe('bar'); })); });
我希望它会像你期望的那样工作!