From 03be784da54c67b73fbcc31cb5d6a6543b09e652 Mon Sep 17 00:00:00 2001 From: Xinyi Ye Date: Tue, 17 Oct 2023 14:32:21 -0700 Subject: [PATCH] fix: should diagnostic track only when api key is valid --- .../test/browser-client.test.ts | 22 +++++++++++++++++++ .../analytics-core/src/plugins/destination.ts | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/analytics-browser/test/browser-client.test.ts b/packages/analytics-browser/test/browser-client.test.ts index 47072f795..f28671382 100644 --- a/packages/analytics-browser/test/browser-client.test.ts +++ b/packages/analytics-browser/test/browser-client.test.ts @@ -306,6 +306,28 @@ describe('browser-client', () => { expect(diagnosticTrack).toHaveBeenCalledWith(1, 0, core.DIAGNOSTIC_MESSAGES.UNEXPECTED_ERROR); }); + test('should diagnostic track when flush and non 200', async () => { + const transportProvider = { + send: jest.fn().mockImplementationOnce(() => { + return Promise.resolve({ + status: Status.Failed, + statusCode: 500, + }); + }), + }; + + await client.init(apiKey, { + defaultTracking: false, + }).promise; + const diagnosticTrack = jest.spyOn(client.config.diagnosticProvider, 'track'); + client.config.transportProvider = transportProvider; + client.track('event_type', { userId: 'user_0' }); + await client.flush().promise; + + expect(diagnosticTrack).toHaveBeenCalledTimes(1); + expect(diagnosticTrack).toHaveBeenCalledWith(1, 0, core.DIAGNOSTIC_MESSAGES.UNEXPECTED_ERROR); + }); + test.each([ ['api_key', undefined, core.DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS], [undefined, { time: [0] }, core.DIAGNOSTIC_MESSAGES.EVENT_ERROR], diff --git a/packages/analytics-core/src/plugins/destination.ts b/packages/analytics-core/src/plugins/destination.ts index 45d436224..ba3f93e77 100644 --- a/packages/analytics-core/src/plugins/destination.ts +++ b/packages/analytics-core/src/plugins/destination.ts @@ -135,7 +135,6 @@ export class Destination implements DestinationPlugin { async send(list: Context[], useRetry = true) { if (!this.config.apiKey) { - this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.MISSING_API_KEY); return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE); } @@ -213,7 +212,9 @@ export class Destination implements DestinationPlugin { handleInvalidResponse(res: InvalidResponse, list: Context[], useRetry: boolean) { if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) { - this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS); + if (!res.body.error.startsWith(INVALID_API_KEY)) { + this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS); + } if (useRetry) { this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`); }