加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 如何测试AngularJS自定义提供程序

发布时间:2020-12-17 08:59:10 所属栏目:安全 来源:网络整理
导读:有没有人有一个如何单元测试提供程序的示例? 例如: config.js angular.module('app.config',[]) .provider('config',function () { var config = { mode: 'distributed',api: 'path/to/api' }; this.mode = function (type) { if (type) { config.isDistri
有没有人有一个如何单元测试提供程序的示例?

例如:

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');
        });
    });

});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读