在AngularJS测试中交换模块值

3 javascript testing jasmine angularjs

我有一个附有greet工厂的模块:

angular.module('someModule', [])
  .factory('greet', function(name) {
    return function() {
      return 'Hi ' + name + '!';
    }
  });
Run Code Online (Sandbox Code Playgroud)

这个工厂注入一个name是在其他模块中定义的值.

angular.module('someOtherModule', [])
  .value('name', 'example');
Run Code Online (Sandbox Code Playgroud)

在测试这个模块时,我希望能够name多次更改我的注射剂的值(每次测试一次),以便我的测试看起来像:

// In my test file…

// Initialise the module I am testing `greet` upon, and mock the other module which has a `name` value
beforeEach(mocks.module('someModule', function ($provider) {
    $provider.value('name', 'Bob');
}));

var greet

beforeEach(mocks.inject(function ($injector) {
    greet = $injector.get('greet');
});

it('should say "Bob"', function () {
    expect(greet()).toBe('Hi Bob!');
});

// Now I need to change the `name` value to be "Bar" instead

it('should say "Bar"', function () {
    expect(greet()).toBe('Hi Bar!');
});
Run Code Online (Sandbox Code Playgroud)

这怎么可能?

这两个模块由我的app模块组成:

angular.module('app', ['someModule', 'someOtherModule'])
Run Code Online (Sandbox Code Playgroud)

zs2*_*020 6

您可以使用$provide.value('name', 'Bob');注入值.

var myApp = angular.module('myApp', []);

myApp.factory('greet', function (name) {
    return function () {
        return 'Hi ' + name + '!';
    }
});

myApp.value('name', 'example');

describe('myApp', function () {
    beforeEach(angular.mock.module('myApp'));

    it('should say "Bob"', function () {
        module(function ($provide) {
            $provide.value('name', 'Bob');
        });
        angular.mock.inject(function ($injector) {
            var greet = $injector.get('greet');
            expect(greet()).toBe('Hi Bob!');
        })
    });

    it('should say "Bar"', function () {
        module(function ($provide) {
            $provide.value('name', 'Bar');
        });
        angular.mock.inject(function ($injector) {
            var greet = $injector.get('greet');
            expect(greet()).toBe('Hi Bar!');
        })
    });
});
Run Code Online (Sandbox Code Playgroud)

我为你创建了一个演示,并希望它可以解决一些问题!

更新:演示

Demo