-1

I have a file with a variable declared as const:

sendFunction.js

const Analytics = require('analytics-node');
const writeKey = process.env.WRITE_KEY;

//Call Segment service
export const sendAnalytics = () => {
   return new Analytics(writeKey).track({
        userId: clientKey,
        event: USER_EVENT,
        properties: {
            Action: userEvent,
            
        }
    });
}

I have a Jest unit test that is testing the function, and the function required the writeKey so that we can trigger the sendAnalytics() function but I'll get error as writeKey is undefined.

AssertionError [ERR_ASSERTION]: You must pass your Segment project's write key.

sendFunction.test.js


import * as sendFunction from './sendFunction';

test('analytics object should be successfully submitted', async () => {
   let sendAnalyticsSpy;
   sendAnalyticsSpy = jest.spyOn(
     sendFunction,
     'sendAnalytics'
   );
   expect(sendAnalyticsSpy).toHaveBeenCalledTimes(1);
})

As what we have is writeKey was not exported, just a const variable declared in the class. May I know how can I mock the writeKey with Jest?

Leon kong
  • 121
  • 1
  • 2
  • 9

1 Answers1

0

You can try this: https://stackoverflow.com/a/58953365/16068019

Alternatively you could use https://www.npmjs.com/package/dotenv and create an .env file for your test environment that get's loaded when testing.

leonbubova
  • 109
  • 1
  • 4