有没有人有一个如何单元测试提供程序的示例?
例如:
config.js
angular.module('app.config',[]) .provider('config',function () { var config = { mode: 'distributed',api: 'path/to/api' }; this.mode = function (type) { if (type) { config.isDistributedInstance = type === config.mode; config.isLocalInstance = !config.isDistributedInstance; config.mode = type; return this; } else { return config.mode; } }; this.$get = function () { return config; }; }]);
app.js
angular.module('app',['app.config']) .config(['configProvider',function (configProvider) { configProvider.mode('local'); }]);
app.js在测试中使用,我看到已配置的configProvider,我可以测试它作为服务。但是如何测试配置的能力?或者它根本不需要?
我有这个相同的问题,只找到一个工作的解决方案在这个
Google Group answer,它的参考
fiddle example。
测试你的提供者代码看起来像这样(在fiddle example的代码和为我工作):
describe('Test app.config provider',function () { var theConfigProvider; beforeEach(function () { // Initialize the service provider // by injecting it to a fake module's config block var fakeModule = angular.module('test.app.config',function () {}); fakeModule.config( function (configProvider) { theConfigProvider = configProvider; }); // Initialize test.app injector module('app.config','test.app.config'); // Kickstart the injectors prevIoUsly registered // with calls to angular.mock.module inject(function () {}); }); describe('with custom configuration',function () { it('tests the providers internal function',function () { // check sanity expect(theConfigProvider).not.toBeUndefined(); // configure the provider theConfigProvider.mode('local'); // test an instance of the provider for // the custom configuration changes expect(theConfigProvider.$get().mode).toBe('local'); }); }); });