') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); chore(shared): Improve test coverage by LekoArts · Pull Request #1925 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/grumpy-swans-taste.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@clerk/shared": patch
---

Improve internal test coverage and fix small bug inside `callWithRetry`
59 changes: 58 additions & 1 deletion packages/shared/src/__tests__/browser.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,66 @@
import { inBrowser, isValidBrowserOnline, userAgentIsRobot } from '../browser';
import { inBrowser, isValidBrowser, isValidBrowserOnline, userAgentIsRobot } from '../browser';

describe('inBrowser()', () => {
afterEach(() => {
jest.restoreAllMocks();
});

it('returns true if window is defined', () => {
expect(inBrowser()).toBe(true);
});
it('returns false if window is undefined', () => {
const windowSpy = jest.spyOn(global, 'window', 'get');
// @ts-ignore - Test
windowSpy.mockReturnValue(undefined);
expect(inBrowser()).toBe(false);
});
});

describe('isValidBrowser', () => {
let userAgentGetter: any;
let webdriverGetter: any;

beforeEach(() => {
userAgentGetter = jest.spyOn(window.navigator, 'userAgent', 'get');
webdriverGetter = jest.spyOn(window.navigator, 'webdriver', 'get');
});

afterEach(() => {
jest.restoreAllMocks();
});

it('returns false if not in browser', () => {
const windowSpy = jest.spyOn(global, 'window', 'get');
// @ts-ignore - Test
windowSpy.mockReturnValue(undefined);

expect(isValidBrowser()).toBe(false);
});

it('returns true if in browser, navigator is not a bot, and webdriver is not enabled', () => {
userAgentGetter.mockReturnValue(
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0',
);
webdriverGetter.mockReturnValue(false);

expect(isValidBrowser()).toBe(true);
});

it('returns false if navigator is a bot', () => {
userAgentGetter.mockReturnValue('msnbot-NewsBlogs/2.0b (+http://search.msn.com/msnbot.htm)');
webdriverGetter.mockReturnValue(false);

expect(isValidBrowser()).toBe(false);
});

it('returns false if webdriver is enabled', () => {
userAgentGetter.mockReturnValue(
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0',
);
webdriverGetter.mockReturnValue(true);

expect(isValidBrowser()).toBe(false);
});
});

describe('detectUserAgentRobot', () => {
Expand Down
23 changes: 23 additions & 0 deletions packages/shared/src/__tests__/callWithRetry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
import { callWithRetry } from '../callWithRetry';

describe('callWithRetry', () => {
test('should return the result of the function if it succeeds', async () => {
const fn = jest.fn().mockResolvedValue('result');
const result = await callWithRetry(fn);
expect(result).toBe('result');
expect(fn).toHaveBeenCalledTimes(1);
});

test('should retry the function if it fails', async () => {
const fn = jest.fn().mockRejectedValueOnce(new Error('error')).mockResolvedValueOnce('result');
const result = await callWithRetry(fn, 1, 2);
expect(result).toBe('result');
expect(fn).toHaveBeenCalledTimes(2);
});

test('should throw an error if the function fails too many times', async () => {
const fn = jest.fn().mockRejectedValue(new Error('error'));
await expect(callWithRetry(fn, 1, 2)).rejects.toThrow('error');
expect(fn).toHaveBeenCalledTimes(2);
});
});
30 changes: 30 additions & 0 deletions packages/shared/src/__tests__/keys.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import {
buildPublishableKey,
createDevOrStagingUrlCache,
isDevelopmentFromApiKey,
isLegacyFrontendApiKey,
isProductionFromApiKey,
isPublishableKey,
parsePublishableKey,
} from '../keys';
Expand DownExpand Up@@ -90,3 +92,31 @@ describe('isDevOrStagingUrl(url)', () => {
expect(isDevOrStagingUrl(a)).toBe(expected);
});
});

describe('isDevelopmentFromApiKey(key)', () => {
const cases: Array<[string, boolean]> = [
['sk_live_Y2xlcmsuY2xlcmsuZGV2JA==', false],
['sk_test_Y2xlcmsuY2xlcmsuZGV2JA==', true],
['live_Y2xlcmsuY2xlcmsuZGV2JA==', false],
['test_Y2xlcmsuY2xlcmsuZGV2JA==', true],
];

test.each(cases)('given %p as a publishable key string, returns %p', (publishableKeyStr, expected) => {
const result = isDevelopmentFromApiKey(publishableKeyStr);
expect(result).toEqual(expected);
});
});

describe('isProductionFromApiKey(key)', () => {
const cases: Array<[string, boolean]> = [
['sk_live_Y2xlcmsuY2xlcmsuZGV2JA==', true],
['sk_test_Y2xlcmsuY2xlcmsuZGV2JA==', false],
['live_Y2xlcmsuY2xlcmsuZGV2JA==', true],
['test_Y2xlcmsuY2xlcmsuZGV2JA==', false],
];

test.each(cases)('given %p as a publishable key string, returns %p', (publishableKeyStr, expected) => {
const result = isProductionFromApiKey(publishableKeyStr);
expect(result).toEqual(expected);
});
});
58 changes: 57 additions & 1 deletion packages/shared/src/__tests__/url.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { addClerkPrefix, parseSearchParams, stripScheme } from '../url';
import { addClerkPrefix, getClerkJsMajorVersionOrTag, getScriptUrl, parseSearchParams, stripScheme } from '../url';

describe('parseSearchParams(queryString)', () => {
it('parses query string and returns a URLSearchParams object', () => {
Expand DownExpand Up@@ -56,3 +56,59 @@ describe('addClerkPrefix(str)', () => {
expect(addClerkPrefix(urlInput)).toBe(urlOutput);
});
});

describe('getClerkJsMajorVersionOrTag', () => {
const stagingFrontendApi = 'foobar.lclstage.dev';

it('returns staging if pkgVersion is not provided and frontendApi is staging', () => {
expect(getClerkJsMajorVersionOrTag(stagingFrontendApi)).toBe('staging');
});

it('returns latest if pkgVersion is not provided and frontendApi is not staging', () => {
expect(getClerkJsMajorVersionOrTag('foobar.dev')).toBe('latest');
});

it('returns next if pkgVersion contains next', () => {
expect(getClerkJsMajorVersionOrTag('foobar.dev', '1.2.3-next.4')).toBe('next');
});

it('returns the major version if pkgVersion is provided', () => {
expect(getClerkJsMajorVersionOrTag('foobar.dev', '1.2.3')).toBe('1');
});

it('returns latest if pkgVersion is empty string', () => {
expect(getClerkJsMajorVersionOrTag('foobar.dev', '')).toBe('latest');
});
});

describe('getScriptUrl', () => {
const frontendApi = 'https://foobar.dev';

it('returns URL using the clerkJSVersion if provided', () => {
expect(getScriptUrl(frontendApi, { clerkJSVersion: '1.2.3' })).toBe(
'https://foobar.dev/npm/@clerk/clerk-js@1.2.3/dist/clerk.browser.js',
);
});

it('returns URL using the latest version if clerkJSVersion & pkgVersion is not provided + frontendApi is not staging', () => {
expect(getScriptUrl(frontendApi, {})).toBe('https://foobar.dev/npm/@clerk/clerk-js@latest/dist/clerk.browser.js');
});

it('returns URL using the major version if only pkgVersion is provided', () => {
expect(getScriptUrl(frontendApi, { pkgVersion: '1.2.3' })).toBe(
'https://foobar.dev/npm/@clerk/clerk-js@1/dist/clerk.browser.js',
);
});

it('returns URL using the major version if only pkgVersion contains next', () => {
expect(getScriptUrl(frontendApi, { pkgVersion: '1.2.3-next.4' })).toBe(
'https://foobar.dev/npm/@clerk/clerk-js@next/dist/clerk.browser.js',
);
});

it('returns URL using the staging tag if frontendApi is staging', () => {
expect(getScriptUrl('https://foobar.lclstage.dev', {})).toBe(
'https://foobar.lclstage.dev/npm/@clerk/clerk-js@staging/dist/clerk.browser.js',
);
});
});
2 changes: 1 addition & 1 deletion packages/shared/src/callWithRetry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,6 @@ export async function callWithRetry<T>(
}
await wait(2 ** attempt * 100);

return callWithRetry(fn, attempt + 1);

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests actually uncovered this small bug here

return callWithRetry(fn, attempt + 1, maxAttempts);
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
import { createDeferredPromise } from '../createDeferredPromise';

describe('createDeferredPromise', () => {
test('resolves with correct value', async () => {
const { promise, resolve } = createDeferredPromise();
const expectedValue = 'hello world';
resolve(expectedValue);
const result = await promise;
expect(result).toBe(expectedValue);
});

test('rejects with correct error', async () => {
const { promise, reject } = createDeferredPromise();
const expectedError = new Error('something went wrong');
reject(expectedError);
try {
await promise;
} catch (error) {
expect(error).toBe(expectedError);
}
});
});
20 changes: 20 additions & 0 deletions packages/shared/src/utils/__tests__/instance.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { isStaging } from '../instance';

describe('isStaging', () => {
it.each([
['clerk', false],
['clerk.com', false],
['whatever.com', false],
['clerk.abcef', false],
['clerk.abcef.12345', false],
['clerk.abcef.12345.lcl', false],
['clerk.abcef.12345.lcl.dev', false],
['clerk.abcef.12345.stg.dev', false],
['clerk.abcef.12345.lclstage.dev', true],
['clerk.abcef.12345.stgstage.dev', true],
['clerk.abcef.12345.clerkstage.dev', true],
['clerk.abcef.12345.accountsstage.dev', true],
])('validates the frontendApi format', (str, expected) => {
expect(isStaging(str)).toBe(expected);
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
import { runWithExponentialBackOff } from '../runWithExponentialBackOff';

describe('runWithExponentialBackOff', () => {
test('resolves with the result of the callback', async () => {
const result = await runWithExponentialBackOff(() => Promise.resolve('success'));
expect(result).toBe('success');
});

test('retries the callback until it succeeds', async () => {
let attempts = 0;
const result = await runWithExponentialBackOff(() => {
attempts++;
if (attempts < 3) {
throw new Error('failed');
}
return Promise.resolve('success');
});
expect(result).toBe('success');
expect(attempts).toBe(3);
});
});
3 changes: 3 additions & 0 deletions packages/shared/src/utils/instance.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
/**
* Check if the frontendApi ends with a staging domain
*/
export function isStaging(frontendApi: string): boolean {
return (
frontendApi.endsWith('.lclstage.dev') ||
Expand Down