diff --git a/package.json b/package.json index 621a00ce75..ef419e25cd 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "main": "./website/src/server.js", "dependencies": { "amazon-payments": "0.0.4", + "amplitude": "^1.0.3", "async": "~0.9.0", "aws-sdk": "^2.0.25", "babel": "^5.5.4", diff --git a/test/server_side/analytics.test.js b/test/server_side/analytics.test.js new file mode 100644 index 0000000000..fa28579ab2 --- /dev/null +++ b/test/server_side/analytics.test.js @@ -0,0 +1,78 @@ +var sinon = require('sinon'); +var chai = require("chai") +chai.use(require("sinon-chai")) +var expect = chai.expect +var rewire = require('rewire'); + +describe('analytics', function() { + var amplitudeMock = sinon.stub(); + + describe('init', function() { + var analytics = rewire('../../website/src/analytics'); + + beforeEach(function() { + analytics.__set__('Amplitude', amplitudeMock); + }); + + afterEach(function(){ + amplitudeMock.reset(); + }); + + it('throws an error if no options are passed in', function() { + expect(analytics.init).to.throw('No options provided'); + }); + + it('registers amplitude with token', function() { + var options = { + amplitudeToken: 'token', + uuid: 'user-id' + }; + analytics.init(options); + + expect(amplitudeMock).to.be.calledOnce; + expect(amplitudeMock).to.be.calledWith('token', 'user-id'); + }); + + it('does not register amplitude without token', function() { + var options = { uuid: 'user-id' }; + analytics.init(options); + + expect(amplitudeMock).to.not.be.called; + }); + }); + + describe('track', function() { + var analytics = rewire('../../website/src/analytics'); + + context('amplitude not initialized', function() { + it('throws error', function() { + expect(analytics.track).to.throw('Amplitude not initialized'); + }); + }); + + context('amplitude initialized', function() { + var amplitudeTrack = sinon.stub(); + + beforeEach(function() { + analytics.__set__('Amplitude', amplitudeMock); + analytics.init({amplitudeToken: 'token', uuid: 'user-id'}); + analytics.__set__('amplitude.track', amplitudeTrack); + }); + + afterEach(function(){ + amplitudeMock.reset(); + }); + + it('tracks event in amplitude', function() { + var data = { + foo: 'bar' + }; + + analytics.track(data); + + expect(amplitudeTrack).to.be.calledOnce; + expect(amplitudeTrack).to.be.calledWith(data); + }); + }); + }); +}); diff --git a/website/src/analytics.js b/website/src/analytics.js new file mode 100644 index 0000000000..0fac3db680 --- /dev/null +++ b/website/src/analytics.js @@ -0,0 +1,22 @@ +var Amplitude = require('amplitude'); +var amplitude; + +var analytics = { + init: init, + track: track +} + +function init(options) { + if(!options) { throw 'No options provided' } + + if(options.amplitudeToken) { + amplitude = new Amplitude(options.amplitudeToken, options.uuid); + } +} + +function track(data) { + if(!amplitude) throw 'Amplitude not initialized'; + amplitude.track(data); +} + +module.exports = analytics;