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?