Skip to content

Commit

Permalink
make tests a bit less flake
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky committed Dec 6, 2022
1 parent 826597b commit 38e5de8
Show file tree
Hide file tree
Showing 13 changed files with 621 additions and 171 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"jest": "^28.1.0",
"lint-staged": "^13.0.0",
"lodash": "^4.17.21",
"nock": "^13.2.9",
"node-gyp": "^9.0.0",
"prettier": "^2.6.2",
"ts-jest": "^28.0.4",
Expand Down
1 change: 1 addition & 0 deletions packages/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
},
"devDependencies": {
"@internal/config": "0.0.0",
"@segment/analytics.js-integration": "^3.3.3",
"@segment/analytics.js-integration-amplitude": "^3.3.3",
"@segment/inspector-webext": "^2.0.3",
"@size-limit/preset-big-lib": "^7.0.8",
Expand Down
187 changes: 27 additions & 160 deletions packages/browser/src/browser/__tests__/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,34 @@ import { AnalyticsBrowser, loadLegacySettings } from '..'
import { isOffline } from '../../core/connection'
import * as SegmentPlugin from '../../plugins/segmentio'
import jar from 'js-cookie'
import {
AMPLITUDE_WRITEKEY,
TEST_WRITEKEY,
} from '../../test-helpers/test-writekeys'
import { PriorityQueue } from '../../lib/priority-queue'
import { getCDN, setGlobalCDNUrl } from '../../lib/parse-cdn'
import { clearAjsBrowserStorage } from '../../test-helpers/browser-storage'
import { ActionDestination } from '@/plugins/remote-loader'
import { ClassicIntegrationBuilder } from '../../plugins/ajs-destination/types'
import { createSuccess } from '../../test-helpers/factories'
import { cdnSettingsKitchenSink } from '../../test-helpers/fixtures/cdn-settings'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let fetchCalls: Array<any>[] = []
// Mock unfetch so we can record any http requests made

jest.mock('unfetch', () => {
const originalModule = jest.requireActual('unfetch')
return {
__esModule: true,
...originalModule,
default: (...args: unknown[]) => {
fetchCalls.push(args)
return originalModule.apply(originalModule, args)
default: (url: string, req?: Request) => {
fetchCalls.push([url, req])

if (!req || req.method === 'get') {
// GET https://cdn.segment.com/v1/projects/{writeKey}
return createSuccess(cdnSettingsKitchenSink)
}

if (req?.method === 'post') {
// POST https://api.segment.io/v1/{event.type}
return createSuccess({ success: true }, { status: 201 })
}

throw new Error(
`no match found for request (url:${url}, req:${JSON.stringify(req)})`
)
},
}
})
Expand Down Expand Up @@ -87,7 +94,8 @@ const enrichBilling: Plugin = {
},
}

const writeKey = TEST_WRITEKEY
const writeKey = 'foo'
const amplitudeWriteKey = 'bar'

beforeEach(() => {
setGlobalCDNUrl(undefined as any)
Expand Down Expand Up @@ -680,7 +688,7 @@ describe('addDestinationMiddleware', () => {
'amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
apiKey: amplitudeWriteKey,
},
{}
)
Expand Down Expand Up @@ -823,7 +831,7 @@ describe('deregister', () => {
'amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
apiKey: amplitudeWriteKey,
},
{}
)
Expand Down Expand Up @@ -868,7 +876,7 @@ describe('retries', () => {

it('does not retry errored events if retryQueue setting is set to false', async () => {
const [ajs] = await AnalyticsBrowser.load(
{ writeKey: TEST_WRITEKEY },
{ writeKey: writeKey },
{ retryQueue: false }
)

Expand Down Expand Up @@ -951,147 +959,6 @@ describe('Segment.io overrides', () => {
})
})

describe('.Integrations', () => {
beforeEach(async () => {
jest.restoreAllMocks()
jest.resetAllMocks()

const html = `
<!DOCTYPE html>
<head>
<script>'hi'</script>
</head>
<body>
</body>
</html>
`.trim()

const jsd = new JSDOM(html, {
runScripts: 'dangerously',
resources: 'usable',
url: 'https://localhost',
})

const windowSpy = jest.spyOn(global, 'window', 'get')
windowSpy.mockImplementation(
() => jsd.window as unknown as Window & typeof globalThis
)

const documentSpy = jest.spyOn(global, 'document', 'get')
documentSpy.mockImplementation(
() => jsd.window.document as unknown as Document
)
})

it('lists all legacy destinations', async () => {
const amplitude = new LegacyDestination(
'Amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
},
{}
)

const ga = new LegacyDestination('Google-Analytics', 'latest', {}, {})

const [analytics] = await AnalyticsBrowser.load({
writeKey,
plugins: [amplitude, ga],
})

await analytics.ready()

expect(analytics.Integrations).toMatchInlineSnapshot(`
Object {
"Amplitude": [Function],
"Google-Analytics": [Function],
}
`)
})

it('catches destinations with dots in their names', async () => {
const amplitude = new LegacyDestination(
'Amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
},
{}
)

const ga = new LegacyDestination('Google-Analytics', 'latest', {}, {})
const customerIO = new LegacyDestination('Customer.io', 'latest', {}, {})

const [analytics] = await AnalyticsBrowser.load({
writeKey,
plugins: [amplitude, ga, customerIO],
})

await analytics.ready()

expect(analytics.Integrations).toMatchInlineSnapshot(`
Object {
"Amplitude": [Function],
"Customer.io": [Function],
"Google-Analytics": [Function],
}
`)
})

it('uses directly provided classic integrations without fetching them from cdn', async () => {
const amplitude = // @ts-ignore
(await import('@segment/analytics.js-integration-amplitude')).default

const intializeSpy = jest.spyOn(amplitude.prototype, 'initialize')
const trackSpy = jest.spyOn(amplitude.prototype, 'track')

const [analytics] = await AnalyticsBrowser.load(
{
writeKey,
classicIntegrations: [
amplitude as unknown as ClassicIntegrationBuilder,
],
},
{
integrations: {
Amplitude: {
apiKey: 'abc',
},
},
}
)

await analytics.ready()
expect(intializeSpy).toHaveBeenCalledTimes(1)

await analytics.track('test event')

expect(trackSpy).toHaveBeenCalledTimes(1)
})

it('ignores directly provided classic integrations if settings for them are unavailable', async () => {
const amplitude = // @ts-ignore
(await import('@segment/analytics.js-integration-amplitude')).default

const intializeSpy = jest.spyOn(amplitude.prototype, 'initialize')
const trackSpy = jest.spyOn(amplitude.prototype, 'track')

const [analytics] = await AnalyticsBrowser.load({
writeKey,
classicIntegrations: [amplitude as unknown as ClassicIntegrationBuilder],
})

await analytics.ready()

expect(intializeSpy).not.toHaveBeenCalled()

await analytics.track('test event')

expect(trackSpy).not.toHaveBeenCalled()
})
})

describe('Options', () => {
beforeEach(async () => {
jest.restoreAllMocks()
Expand Down Expand Up @@ -1129,7 +996,7 @@ describe('Options', () => {
'amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
apiKey: amplitudeWriteKey,
},
{}
)
Expand Down Expand Up @@ -1165,7 +1032,7 @@ describe('Options', () => {
'amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
apiKey: amplitudeWriteKey,
},
initOptions
)
Expand Down Expand Up @@ -1201,7 +1068,7 @@ describe('Options', () => {
'amplitude',
'latest',
{
apiKey: AMPLITUDE_WRITEKEY,
apiKey: amplitudeWriteKey,
},
initOptions
)
Expand Down
Loading

0 comments on commit 38e5de8

Please sign in to comment.