aleross / angular-segment-analytics

AngularJS module for easily adding Segment analytics to any app. https://segment.com
MIT License
43 stars 14 forks source link

Error: Attempting to load Segment twice for Karma Jasmine Tests #5

Closed dennislo closed 8 years ago

dennislo commented 8 years ago

I'm trying to include route change tracking for UI-Router events in the run() method, like below:

  angular
    .module('enterprise')
    .run(onRun);

  function onRun($rootScope, segment) {
    var deregistrationCallback = $rootScope.$on('$stateChangeSuccess', function() {
        segment.page();   
    });

    $rootScope.$on('$destroy', deregistrationCallback);
  }

However, my karma jasmine tests are throwing these errors:

PhantomJS 1.9.8 (Mac OS X 0.0.0) service: trackingService tests
        Error: Attempting to load Segment twice.
aleross commented 8 years ago

Can you share the code you use to set up your tests? Specifically how you initialize your module and/or ngSegment in the beforeEach of your test script.

Usually you'd have something like:

beforeEach(function () {
    module('myModule');
    // other initialization code
});

The Attempting to load Segment twice error is thrown either when the Segment Analytics.js script has already been included on the page (which sets analytics.initialized to true), or when segmentLoader.load() is called twice. I think it may be that the same instance of the segment loader is being used in two tests.

dennislo commented 8 years ago

Here is my test code:

(function() {
  'use strict';

  describe('service: resultService', function() {
    var resultService;

    // Load the service's module
    beforeEach(module('enterprise'));

    beforeEach(inject(function(_resultService_) {
      // Initialise injectables
      resultService = _resultService_;
    }));

    it('should exist', function() {
      expect(!!resultService).toBe(true);
      expect(resultService.getStudy).toBeDefined();
    });

  });
})();

Here is the error produced by the failing test:

PhantomJS 1.9.8 (Mac OS X 0.0.0) service: resultService should exist FAILED
    Error: Attempting to load Segment twice.
        at /Users/dennislo/app/bower_components/angular-segment-analytics/segment.min.js:1

I looked at your tests, I actually don't have even load ngSegment in the beforeEach of my test scripts, like you do in your tests like: https://github.com/aleross/angular-segment-analytics/blob/master/test/segmentLoaderSpec.js#L5

I tried adding window.analytics.initialized = false; to a few of my test scripts beforeEach and it makes them pass, but I feel as though this isn't really the desirable solution.