Skip to content

Commit

Permalink
Finished modifying tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelGHSeg committed Jun 29, 2023
1 parent b9c4cec commit 1abd1e4
Show file tree
Hide file tree
Showing 12 changed files with 177 additions and 109 deletions.
4 changes: 2 additions & 2 deletions packages/node/src/__tests__/callback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('Callback behavior', () => {
it('should handle success', async () => {
const ajs = createTestAnalytics({
maxEventsInBatch: 1,
customclient: testClient,
customClient: testClient,
})
const ctx = await new Promise<Context>((resolve, reject) =>
ajs.track(
Expand All @@ -37,7 +37,7 @@ describe('Callback behavior', () => {
testClient.returnValue = createError()
const ajs = createTestAnalytics({
maxEventsInBatch: 1,
customclient: testClient,
customClient: testClient,
})
const [err, ctx] = await new Promise<[any, Context]>((resolve) =>
ajs.track(
Expand Down
4 changes: 2 additions & 2 deletions packages/node/src/__tests__/disable.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('disable', () => {
it('should call fetch if disabled is false', async () => {
const analytics = createTestAnalytics({
disable: false,
customclient: checkFetchClient,
customClient: checkFetchClient,
})
checkFetchClient.wasCalled = false
await new Promise((resolve) =>
Expand All @@ -49,7 +49,7 @@ describe('disable', () => {
it('should not call fetch if disabled is true', async () => {
const analytics = createTestAnalytics({
disable: true,
customclient: checkFetchClient,
customClient: checkFetchClient,
})
checkFetchClient.wasCalled = false
await new Promise((resolve) =>
Expand Down
26 changes: 17 additions & 9 deletions packages/node/src/__tests__/emitter.integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const fetcher = jest.fn()
jest.mock('../lib/fetch', () => ({ fetch: fetcher }))

import { createError, createSuccess } from './test-helpers/factories'
import {
createError,
createSuccess,
TestFetchClient,
} from './test-helpers/factories'
import { createTestAnalytics } from './test-helpers/create-test-analytics'
import { assertHttpRequestEmittedEvent } from './test-helpers/assert-shape'

describe('http_request', () => {
const testClient = new TestFetchClient()
it('emits an http_request event if success', async () => {
fetcher.mockReturnValue(createSuccess())
testClient.returnValue = createSuccess()
const analytics = createTestAnalytics()
const fn = jest.fn()
analytics.on('http_request', fn)
Expand All @@ -19,8 +21,11 @@ describe('http_request', () => {
})

it('emits an http_request event if error', async () => {
fetcher.mockReturnValue(createError())
const analytics = createTestAnalytics({ maxRetries: 0 })
testClient.returnValue = createError()
const analytics = createTestAnalytics({
maxRetries: 0,
customClient: testClient,
})
const fn = jest.fn()
analytics.on('http_request', fn)
await new Promise((resolve) =>
Expand All @@ -30,8 +35,11 @@ describe('http_request', () => {
})

it('if error, emits an http_request event on every retry', async () => {
fetcher.mockReturnValue(createError())
const analytics = createTestAnalytics({ maxRetries: 2 })
testClient.returnValue = createError()
const analytics = createTestAnalytics({
maxRetries: 2,
customClient: testClient,
})
const fn = jest.fn()
analytics.on('http_request', fn)
await new Promise((resolve) =>
Expand Down
18 changes: 10 additions & 8 deletions packages/node/src/__tests__/graceful-shutdown-integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { createSuccess } from './test-helpers/factories'
import { TestFetchClient, createSuccess } from './test-helpers/factories'
import { performance as perf } from 'perf_hooks'

const fetcher = jest.fn()
jest.mock('../lib/fetch', () => ({ fetch: fetcher }))

import { Analytics } from '../app/analytics-node'
import { sleep } from './test-helpers/sleep'
import { Plugin, SegmentEvent } from '../app/types'
Expand All @@ -17,18 +13,21 @@ const testPlugin: Plugin = {
isLoaded: () => true,
}

const testClient = new TestFetchClient()

describe('Ability for users to exit without losing events', () => {
let ajs!: Analytics
beforeEach(async () => {
fetcher.mockReturnValue(createSuccess())
testClient.reset()
ajs = new Analytics({
writeKey: 'abc123',
maxEventsInBatch: 1,
customClient: testClient,
})
})
const _helpers = {
getFetchCalls: (mockedFetchFn = fetcher) =>
mockedFetchFn.mock.calls.map(([url, request]) => ({
getFetchCalls: (client = testClient) =>
client.calls.map(([url, request]) => ({
url,
method: request.method,
headers: request.headers,
Expand Down Expand Up @@ -89,6 +88,7 @@ describe('Ability for users to exit without losing events', () => {
ajs = new Analytics({
writeKey: 'abc123',
flushInterval,
customClient: testClient,
})
const closeAndFlushTimeout = ajs['_closeAndFlushDefaultTimeout']
expect(closeAndFlushTimeout).toBe(flushInterval * 1.25)
Expand Down Expand Up @@ -190,6 +190,7 @@ describe('Ability for users to exit without losing events', () => {
writeKey: 'foo',
flushInterval: 10000,
maxEventsInBatch: 15,
customClient: testClient,
})
_helpers.makeTrackCall(analytics)
_helpers.makeTrackCall(analytics)
Expand Down Expand Up @@ -220,6 +221,7 @@ describe('Ability for users to exit without losing events', () => {
writeKey: 'foo',
flushInterval: 10000,
maxEventsInBatch: 15,
customClient: testClient,
})
await analytics.register(_testPlugin)
_helpers.makeTrackCall(analytics)
Expand Down
26 changes: 15 additions & 11 deletions packages/node/src/__tests__/integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
const fetcher = jest.fn()
jest.mock('../lib/fetch', () => ({ fetch: fetcher }))

import { Plugin } from '../app/types'
import { resolveCtx } from './test-helpers/resolve-ctx'
import { testPlugin } from './test-helpers/test-plugin'
import { createSuccess, createError } from './test-helpers/factories'
import { createError, TestFetchClient } from './test-helpers/factories'
import { createTestAnalytics } from './test-helpers/create-test-analytics'

const writeKey = 'foo'
jest.setTimeout(10000)
const timestamp = new Date()

const testClient = new TestFetchClient()

beforeEach(() => {
fetcher.mockReturnValue(createSuccess())
testClient.reset()
})

describe('Settings / Configuration Init', () => {
Expand All @@ -28,11 +27,12 @@ describe('Settings / Configuration Init', () => {
const analytics = createTestAnalytics({
host: 'http://foo.com',
path: '/bar',
customClient: testClient,
})
const track = resolveCtx(analytics, 'track')
analytics.track({ event: 'foo', userId: 'sup' })
await track
expect(fetcher.mock.calls[0][0]).toBe('http://foo.com/bar')
expect(testClient.calls[0][0]).toBe('http://foo.com/bar')
})

it('throws if host / path is bad', async () => {
Expand All @@ -52,11 +52,15 @@ describe('Error handling', () => {
expect(() => analytics.track({} as any)).toThrowError(/event/i)
})

it('should emit on an error', async () => {
const analytics = createTestAnalytics({ maxRetries: 0 })
fetcher.mockReturnValue(
createError({ statusText: 'Service Unavailable', status: 503 })
)
it.only('should emit on an error', async () => {
const analytics = createTestAnalytics({
maxRetries: 0,
customClient: testClient,
})
testClient.returnValue = createError({
statusText: 'Service Unavailable',
status: 503,
})
try {
const promise = resolveCtx(analytics, 'track')
analytics.track({ event: 'foo', userId: 'sup' })
Expand Down
9 changes: 4 additions & 5 deletions packages/node/src/__tests__/plugins.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
const fetcher = jest.fn()
jest.mock('../lib/fetch', () => ({ fetch: fetcher }))

import { createSuccess } from './test-helpers/factories'
import { TestFetchClient } from './test-helpers/factories'
import { createTestAnalytics } from './test-helpers/create-test-analytics'

const testClient = new TestFetchClient()

describe('Plugins', () => {
beforeEach(() => {
fetcher.mockReturnValue(createSuccess())
testClient.reset()
})

describe('Initialize', () => {
Expand Down
31 changes: 30 additions & 1 deletion packages/node/src/__tests__/test-helpers/factories.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isNil } from 'lodash'
import { CustomHTTPClient } from '../../lib/customhttpclient'

export const createSuccess = (body?: any) => {
Expand All @@ -19,11 +20,39 @@ export const createError = (overrides: Partial<Response> = {}) => {
}

export class TestFetchClient implements CustomHTTPClient {
public callCount = 0

public calls = <any[]>[]
get lastCall() {
return this.calls.slice(-1)[0]
}

private _returnValue: any
set returnValue(value: any) {
this._returnValue = value
}

private _errorValue: any
set errorValue(value: any) {
this._errorValue = value
}

public reset() {
this.callCount = 0
this.calls = []
this._returnValue = null
this._errorValue = null
}

send = async (_resource: any, _options: any): Promise<Response> => {
return this._returnValue
this.calls.push([_resource, _options])
this.callCount++
if (this._errorValue) {
throw this._errorValue
}
if (this._returnValue) {
return this._returnValue
}
return createSuccess()
}
}
2 changes: 1 addition & 1 deletion packages/node/src/app/analytics-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class Analytics extends NodeEmitter implements CoreAnalytics {
httpRequestTimeout: settings.httpRequestTimeout,
disable: settings.disable,
flushInterval,
customclient: settings.customclient ?? new DefaultFetchClient(),
customclient: settings.customClient ?? new DefaultFetchClient(),
},
this as NodeEmitter
)
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/app/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export interface AnalyticsSettings {
* Default: DefaultFetchClient which will use the existing global fetch, or
* node-fetch if it doesn't exist
*/
customclient?: CustomHTTPClient
customClient?: CustomHTTPClient
}

export const validateSettings = (settings: AnalyticsSettings) => {
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/lib/__tests__/abort.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { abortSignalAfterTimeout } from '../abort'
import nock from 'nock'
import { sleep } from '@segment/analytics-core'
import { DefaultFetchClient } from '../customhttpclient'

describe(abortSignalAfterTimeout, () => {
const HOST = 'https://foo.com'
Expand Down
Loading

0 comments on commit 1abd1e4

Please sign in to comment.