Skip to content

Commit

Permalink
chore(core): manual fix linter reported errors under __tests__
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF committed Mar 11, 2024
1 parent 22b117b commit 7cb4d22
Show file tree
Hide file tree
Showing 26 changed files with 368 additions and 196 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ module.exports = {
allow: [
// exceptions for core package
'phone_number',
'search_indices',
// exceptions for api packages
'graphql_headers',
// exceptions for the legacy config
Expand Down
72 changes: 43 additions & 29 deletions packages/core/__tests__/BackgroundProcessManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();

const resultPromise = manager.add(async () => {
return new Promise((resolve, raise) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
raise(new Error('a fuss'));
reject(new Error('a fuss'));
}, 50);
});
});
Expand Down Expand Up @@ -146,7 +146,7 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();

// add a job that will not have completed by the time we open() again
manager.add(async () => new Promise(unsleep => setTimeout(unsleep, 10)));
manager.add(async () => new Promise(resolve => setTimeout(resolve, 10)));

// close, but don't want, because we want to prove that open() will wait
// internally for close to resolve before re-opening.
Expand Down Expand Up @@ -176,8 +176,15 @@ describe('BackgroundProcessManager', () => {
expect(manager.isClosing).toBe(false);
expect(manager.isClosed).toBe(false);

let unblock;
manager.add(async () => new Promise(_unblock => (unblock = _unblock)));
let unblock: () => void = () => {
// no op
};
manager.add(
async () =>
new Promise<void>(resolve => {
unblock = resolve;
}),
);

expect(manager.state).toEqual(BackgroundProcessManagerState.Open);
expect(manager.isOpen).toBe(true);
Expand All @@ -195,7 +202,7 @@ describe('BackgroundProcessManager', () => {
// promise layers handling by awaiting another promise before the
// manager can register completion.

unblock();
unblock?.();
await new Promise(process.nextTick);

expect(manager.state).toEqual(BackgroundProcessManagerState.Closed);
Expand Down Expand Up @@ -252,8 +259,8 @@ describe('BackgroundProcessManager', () => {
let completed = false;
const manager = new BackgroundProcessManager();

const resultPromise = manager.add(async onTerminate => {
return new Promise<void>((resolve, reject) => {
const _ = manager.add(async (onTerminate: Promise<void>) => {
return new Promise<void>((resolve, _reject) => {
const timer = setTimeout(() => {
// this is the happy path that we plan not to reach in
// this test.
Expand Down Expand Up @@ -290,8 +297,9 @@ describe('BackgroundProcessManager', () => {
let completed = false;
let thrown;
const manager = new BackgroundProcessManager();
const expectedError = new Error('badness happened');

const resultPromise = manager.add(async onTerminate => {
const resultPromise = manager.add(async (onTerminate: Promise<void>) => {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
// this is the happy path that we plan not to reach in
Expand All @@ -305,7 +313,7 @@ describe('BackgroundProcessManager', () => {
// or reject.
onTerminate.then(() => {
clearTimeout(timer);
reject('badness happened');
reject(expectedError);
});
});
});
Expand All @@ -329,7 +337,7 @@ describe('BackgroundProcessManager', () => {

// then making sure the job really really didn't fire.
expect(completed).toBe(false);
expect(thrown).toEqual('badness happened');
expect(thrown).toEqual(expectedError);
});

test('attempts to terminate all, but patiently waits for persistent jobs', async () => {
Expand All @@ -341,7 +349,7 @@ describe('BackgroundProcessManager', () => {
for (let i = 0; i < 10; i++) {
const _i = i;
results.push(false);
manager.add(async onTerminate => {
manager.add(async (onTerminate: Promise<void>) => {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
results[_i] = true;
Expand All @@ -357,7 +365,7 @@ describe('BackgroundProcessManager', () => {

// remember, if a job *does* terminate, it still
// needs resolve/reject to unblock `close()`.
_i > 5 ? resolve() : reject();
_i > 5 ? resolve() : reject(new Error());
}
});
});
Expand All @@ -371,7 +379,9 @@ describe('BackgroundProcessManager', () => {
expect(results.length).toEqual(10); // sanity check
expect(results.filter(v => v === true).length).toBe(5);
expect(terminationAttemptCount).toEqual(10);
expect(resolutions.filter(r => r.status === 'rejected').length).toEqual(3);
expect(
resolutions.filter((r: any) => r.status === 'rejected').length,
).toEqual(3);
});

test('can be used to terminate other types of bg jobs, like zen subscriptions', async () => {
Expand Down Expand Up @@ -418,7 +428,7 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();
let count = 0;

const subscription = new Observable(observer => {
const _ = new Observable(observer => {
const interval = setInterval(() => {
observer.next({});
}, 10);
Expand Down Expand Up @@ -502,7 +512,7 @@ describe('BackgroundProcessManager', () => {

// accumulate a bunch of close promises, only the first of which should
// send the close signal, but all of which should await resolution.
const closes = [0, 1, 2, 3, 4, 5].map(i => manager.close());
const closes = [0, 1, 2, 3, 4, 5].map(_ => manager.close());

// ensure everything has settled
const resolved = await Promise.allSettled(closes);
Expand Down Expand Up @@ -564,7 +574,7 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();

manager.add(
async () => new Promise(unsleep => setTimeout(unsleep, 1)),
async () => new Promise(resolve => setTimeout(resolve, 1)),
'async function',
);

Expand All @@ -579,9 +589,9 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();

manager.add(
async onTerminate =>
new Promise(finishJob => {
onTerminate.then(finishJob);
async (onTerminate: Promise<void>) =>
new Promise(resolve => {
onTerminate.then(resolve);
}),
'cancelable async function',
);
Expand Down Expand Up @@ -635,27 +645,31 @@ describe('BackgroundProcessManager', () => {
const manager = new BackgroundProcessManager();
await manager.close();

await expect(manager.add(async () => {}, 'some job')).rejects.toThrow(
'some job',
);
await expect(
manager.add(async () => {
// no-op
}, 'some job'),
).rejects.toThrow('some job');
});

test('manager closed error shows names of pending items in error', async () => {
const manager = new BackgroundProcessManager();

let unblock;
let unblock: any;
manager.add(
() => new Promise(_unblock => (unblock = _unblock)),
() => new Promise<void>(resolve => (unblock = resolve)),
'blocking job',
);

const close = manager.close();

await expect(manager.add(async () => {}, 'some job')).rejects.toThrow(
'blocking job',
);
await expect(
manager.add(async () => {
// no-op
}, 'some job'),
).rejects.toThrow('blocking job');

unblock();
unblock?.();
await close;
});
});
4 changes: 2 additions & 2 deletions packages/core/__tests__/Cache/StorageCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ describe('StorageCache', () => {
}
}
// create test helpers
const getStorageCache = (config?: CacheConfig) =>
new StorageCacheTest(config);
const getStorageCache = (storageCacheConfig?: CacheConfig) =>
new StorageCacheTest(storageCacheConfig);

beforeAll(() => {
mockGetCurrentSizeKey.mockReturnValue(currentSizeKey);
Expand Down
46 changes: 25 additions & 21 deletions packages/core/__tests__/Cache/StorageCacheCommon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('StorageCacheCommon', () => {
warningThreshold: 0.8,
};
// create spies
const loggerSpy = {
const loggerSpy: Record<string, jest.SpyInstance> = {
debug: jest.spyOn(ConsoleLogger.prototype, 'debug'),
error: jest.spyOn(ConsoleLogger.prototype, 'error'),
warn: jest.spyOn(ConsoleLogger.prototype, 'warn'),
Expand Down Expand Up @@ -57,9 +57,9 @@ describe('StorageCacheCommon', () => {
}
}
// create test helpers
const getStorageCache = (config?: CacheConfig) =>
const getStorageCache = (storageCacheConfig?: CacheConfig) =>
new StorageCacheCommonTest({
config,
config: storageCacheConfig,
keyValueStorage: mockKeyValueStorage,
});

Expand Down Expand Up @@ -464,8 +464,8 @@ describe('StorageCacheCommon', () => {
describe('getItem()', () => {
const value = 'value';
const cache = getStorageCache(config);
const key = 'key';
const prefixedKey = `${keyPrefix}${key}`;
const testKey = 'key';
const testPrefixedKey = `${keyPrefix}${testKey}`;

beforeEach(() => {
mockKeyValueStorageGetItem.mockReturnValue(null);
Expand All @@ -476,11 +476,11 @@ describe('StorageCacheCommon', () => {
JSON.stringify({ data: value }),
);

expect(await cache.getItem(key)).toBe(value);
expect(await cache.getItem(testKey)).toBe(value);
expect(loggerSpy.debug).toHaveBeenCalledWith(
expect.stringContaining(`Get item: key is ${key}`),
expect.stringContaining(`Get item: key is ${testKey}`),
);
expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey);
expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(testPrefixedKey);
});

it('aborts on empty key', async () => {
Expand Down Expand Up @@ -508,39 +508,41 @@ describe('StorageCacheCommon', () => {
}),
);

expect(await cache.getItem(key)).toBeNull();
expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(prefixedKey);
expect(await cache.getItem(testKey)).toBeNull();
expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(
testPrefixedKey,
);
});

it('returns null if not in cache', async () => {
expect(await cache.getItem(key)).toBeNull();
expect(await cache.getItem(testKey)).toBeNull();
});

it('updates item visitedTime when fetched from cache', async () => {
const item = { data: value };
mockKeyValueStorageGetItem.mockReturnValue(JSON.stringify(item));

expect(await cache.getItem(key)).toBe(value);
expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey);
expect(await cache.getItem(testKey)).toBe(value);
expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(testPrefixedKey);
expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith(
prefixedKey,
testPrefixedKey,
JSON.stringify({ ...item, visitedTime: currentTime }),
);
});

it('execute a callback if specified when key not found in cache', async () => {
mockGetByteLength.mockReturnValue(20);
const callback = jest.fn(() => value);
expect(await cache.getItem(key, { callback })).toBe(value);
expect(await cache.getItem(testKey, { callback })).toBe(value);
expect(callback).toHaveBeenCalled();
expect(mockKeyValueStorageSetItem).toHaveBeenCalled();
});
});

describe('removeItem()', () => {
const cache = getStorageCache(config);
const key = 'key';
const prefixedKey = `${keyPrefix}${key}`;
const testKey = 'key';
const testPrefixedKey = `${keyPrefix}${testKey}`;

beforeEach(() => {
mockKeyValueStorageGetItem.mockReturnValue(
Expand All @@ -549,11 +551,13 @@ describe('StorageCacheCommon', () => {
});

it('removes an item', async () => {
await cache.removeItem(key);
await cache.removeItem(testKey);
expect(loggerSpy.debug).toHaveBeenCalledWith(
expect.stringContaining(`Remove item: key is ${key}`),
expect.stringContaining(`Remove item: key is ${testKey}`),
);
expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(
testPrefixedKey,
);
expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(prefixedKey);
});

it('aborts on empty key', async () => {
Expand All @@ -574,7 +578,7 @@ describe('StorageCacheCommon', () => {

it('does nothing if item not found', async () => {
mockKeyValueStorageGetItem.mockReturnValue(null);
await cache.removeItem(key);
await cache.removeItem(testKey);
expect(mockKeyValueStorageRemoveItem).not.toHaveBeenCalled();
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/core/__tests__/Cache/utils/CacheList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ describe('CacheList', () => {
test('get all keys in the list', () => {
const list: CacheList = new CacheList();
const keys: string[] = ['0', '1', '2'];
for (let i = 0; i < keys.length; i++) {
list.insertItem(keys[i]);
for (const key of keys) {
list.insertItem(key);
}

const listKeys: string[] = list.getKeys();
Expand Down
10 changes: 6 additions & 4 deletions packages/core/__tests__/ConsoleLogger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ describe('ConsoleLogger', () => {

it('should do nothing when a non-logging category plugin is provided to addPluggable', () => {
const provider = {
getCategoryName: function () {
getCategoryName: () => {
return 'non-logging';
},
getProviderName: function () {
getProviderName: () => {
return 'lol';
},
configure: function () {
configure: () => {
return {};
},
pushLogs: () => {},
pushLogs: () => {
// no-op
},
} as LoggingProvider;

const logger = new ConsoleLogger('name');
Expand Down
Loading

0 comments on commit 7cb4d22

Please sign in to comment.