Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchanging module values in AngularJS test

I have a module with a greet factory attached to it:

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

This factory injects a name which is a value defined in some other module.

angular.module('someOtherModule', [])
  .value('name', 'example');

When testing this module, I would like to be able to change the value of my injectable name multiple times (once for each test) so that my tests can look something like:

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

How is this possible?

The two modules are composed with my app module:

angular.module('app', ['someModule', 'someOtherModule'])

1 Answers

You can use $provide.value('name', 'Bob'); to inject the value.

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

I created a demo for you and hope it can shed some light!

Updated: demo

Demo

like image 135
zs2020 Avatar answered Mar 18 '26 16:03

zs2020



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!