jeudi 1 novembre 2018

Unit testing of a function with conditional statement

I have a function to track analytics from google analytics. So that in my function i need to see if the code exists or not.

Analytics.js

const gaCode = process.env.REACT_APP_GA_TRACKING_CODE;
const gaCodeExists = gaCode && gaCode.Length > 0;

function trackEvent(category = "Event", name) {
    if(gaCodeExists) {
        GoogleAnalytics.event({
            category,
            action: name,
        });
    }

    return;
}

export default {
    gaCodeExists,
    trackEvent
}

At first I was doing like this (which I am pretty sure I am not doing correctly).

describe('Testing analytics', () => {
    beforeEach(() => {
        Analytics.trackEvent(null, 'Tracking');
    });

    it('should not call google analytics', () => {
        if (!gaCodeExists) {
            const mockGoogleAnalytics = jest.fn(() => GoogleAnalytics.event);
            expect(mockGoogleAnalytics.mock.calls.length).toBe(0);
        }
    });
})

After reading some blog posts and looking at stackover flow questions. I changed it to like this which I think I am mocking the gaCodeExists variable as below.

import constants from '../index';
import { isUsingGoogleAnalytics } from '../index';

describe('Analytics Testing', () => {
    it('Should test trackEvent', () => {
        constants.isUsingGoogleAnalytics = true;
        expect(constants.isUsingGoogleAnalytics).toBe(true);
    });
});

Now I am stuck how can I do the testing on trackEvent function. How can I apply mock gaCodeExists variable to it? The test cases would be if the gaCodeExists is true, expect(mockFunction).toHaveBeenCalled(1).

P.S: I am new to testing.

Aucun commentaire:

Enregistrer un commentaire