如何测试 AngularJS 自定义提供程序 [英] How to test AngularJS custom provider

查看:25
本文介绍了如何测试 AngularJS 自定义提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人有如何对提供程序进行单元测试的示例吗?

Does anyone have an example of how to unit test a provider?

例如:

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 并且我可以将其作为服务进行测试.但是如何测试配置能力呢?还是根本不需要?

app.js is using in tests and I see already configured configProvider and I can test it as a service. But how can I test the ability to configure? Or it does not need at all?

推荐答案

我有同样的问题,只在这个 Google 群组答案 并且引用了 小提琴示例.

I had this same question and only found a working solution in this Google Group answer and it's referenced fiddle example.

测试您的提供程序代码看起来像这样(遵循小提琴示例中的代码以及什么为我工作):

Testing your provider code would look something like this (following the code in the fiddle example and what worked for me):

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

});

这篇关于如何测试 AngularJS 自定义提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆