1

Looking at an example from Mastering Web Applications in AngularJS:

angular.module('archive', [])
  .factory('notificationsArchive', function () {
     var archivedNotifications = [];
     return {
        archive:function (notification) {
            archivedNotifications.push(notification);
        },
        getArchived:function () {
            return archivedNotifications;
        }};
  });

Then, the module's test:

describe('notifications archive tests', function () {
   var notificationsArchive;

   beforeEach(module('archive'));

   beforeEach(inject(function (_notificationsArchive_) {
        notificationsArchive = _notificationsArchive_;
   }));

   it('should give access to the archived items', function () {
       var notification = {msg: 'Old message.'};

    notificationsArchive.archive(notification);

    expect(notificationsArchive.getArchived())
          .toContain(notification);
    });
});

What's going on in the second beforeEach(inject ...?

2 Answers 2

2
beforeEach(inject(function (_notificationsArchive_) {
    notificationsArchive = _notificationsArchive_;
}));

That's just saying before each test, get an instance of notificationsArchive. It then assigns that instance to a variable that can be used in the actual test case. The underscores around notificationsArchive are just syntactic sugar so you don't have to come up with another name for the variable that your test users.

Sign up to request clarification or add additional context in comments.

Comments

2

It is injecting the notificationsArchive service into a function that assigns that service to the local variable "notificationsArchive" before each test. The underscores in the name are ignored.

https://docs.angularjs.org/api/ngMock/function/angular.mock.inject

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.