I am having some issues mocking a Google Analytics client method use Jest. Example A returns undefined within my function. The problem seems to be related to chaining the mockResolvedValueOnce outputs to runReport.
When I format the method as in example B, so just returning a single default value, I do get an output. Why is it that I’m able to return a value when configuring the output within the client, but I’m not able to return anything when configuring the output after the client is initialised?
A.
const { monitorTraffic } = require('../index.js');
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const axios = require('axios');
jest.mock('@google-analytics/data', () => {
return {
BetaAnalyticsDataClient: jest.fn().mockImplementation(() => {
return {
runReport: jest.fn()
};
}),
};
});
jest.mock('axios');
describe('monitorTraffic', () => {
let req;
let res;
let runReportMock;
beforeEach(() => {
req = {};
res = {
status: jest.fn().mockReturnThis(),
send: jest.fn()
};
const analyticsClientInstance = new BetaAnalyticsDataClient();
runReportMock = analyticsClientInstance.runReport;
runReportMock.mockReset();
axios.post.mockReset();
});
it('should send an alert if traffic drops more than the threshold compared to yesterday', async () => {
runReportMock
.mockResolvedValueOnce({ rows: [{ dimensionValues: [{ value: '2024-08-30' }], metricValues: [{ value: '100' }] }] })
.mockResolvedValueOnce({ rows: [{ dimensionValues: [{ value: '2024-08-29' }], metricValues: [{ value: '200' }] }] });
await monitorTraffic(req, res);
// Assertions
expect(runReportMock).toHaveBeenCalledTimes(2); // Ensure runReport is called twice
expect(res.status).not.toHaveBeenCalledWith(500);
expect(axios.post).toHaveBeenCalled();
});
B.
jest.mock('@google-analytics/data', () => {
return {
BetaAnalyticsDataClient: jest.fn().mockImplementation(() => {
return {
runReport: jest.fn()
.mockResolvedValue({
rows: [
{
dimensionValues: [{ value: '2024-08-30' }],
metricValues: [{ value: '100' }]
}
]
})
};
}),
};
});