[英]How to mock a module in angular
So I've read many posts but no suggestions as worked so far. 因此,到目前为止,我已经阅读了许多帖子,但没有建议。
I am wanting to mock a module - say angular-foo. 我想模拟一个模块-说出angular-foo。 The original file is loaded along with everything else.
原始文件将与其他所有文件一起加载。
angular.module('app', ['angular-foo'...
I would like to mock this module in my karma/mocha tests. 我想在我的业力/摩卡测试中模拟这个模块。 I've tried suggestions such as calling it like this but it's a no go.
我已经尝试过像这样称呼它的建议,但这是不行的。
beforeEach(module('app'));
beforeEach(module('angular-foo'))
How can I completely prevent the original angular-foo from running (yet it must load as part of the rest of the code)? 如何完全阻止原始的angular-foo运行(但必须将其作为其余代码的一部分加载)?
To mock factory
, service
and value
services, angular.mock.module
object argument can be used 要模拟
factory
, service
和value
服务,可以使用angular.mock.module
对象参数
beforeEach(module('app', 'angular-foo', {
fooFactoryService: ...,
fooValueService: ...
}));
To mock the services that are available for injection during config phase ( constant
and provider
), config function should be used 为了模拟可在配置阶段注入的服务(
constant
和provider
),应使用配置功能
beforeEach(module('app', 'angular-foo', ($provide) => {
$provide.constant('fooConstantService', ...),
$provide.provider('fooProviderService', ...),
}));
The last module in the row overrides the services from the other ones. 该行中的最后一个模块将覆盖其他模块的服务。 The services can be mocked partially (with
$provide.decorator
) or entirely. 可以部分模拟服务(使用
$provide.decorator
)或完全$provide.decorator
。
If angular-foo
module isn't loaded at all but other modules make use of it, it can be fully redefined in specs with its mocked version with 如果没有加载
angular-foo
模块,但其他模块使用了它,则可以在规范中使用其模拟版本完全重新定义它
angular.module('angular-foo', [])...
beforeEach(module('app', 'angular-foo'));
What did the trick for me was putting the provider before the module declaration: 对我来说,窍门是将提供程序放在模块声明之前:
beforeEach(module(function($provide) {
$provide.provider('myProvider', function() {
return {
myProviderFunction: function() {},
$get: function () {
return {
myProviderFunction: function() {}
};
}
};
});
}));
beforeEach(module('myApp'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.