Skip to content

Commit

Permalink
add commHelper.test.ts
Browse files Browse the repository at this point in the history
-Added one test for `fetchUrlCached` - uses a mocked 'fetch' to simulate retreieving data from a URL. It ensures that the second time this URL is queried, the data comes back faster (because it gets cached in the localStorage after the first call)

Note at the bottom explains why other functions were not tested.
  • Loading branch information
JGreenlee committed Sep 29, 2023
1 parent 5826213 commit 77fe30a
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions www/__tests__/commHelper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { mockLogger } from '../__mocks__/globalMocks';
import { fetchUrlCached } from '../js/commHelper';

mockLogger();

// mock for JavaScript 'fetch'
// we emulate a 100ms delay when i) fetching data and ii) parsing it as text
global.fetch = (url: string) => new Promise((rs, rj) => {
setTimeout(() => rs({
text: () => new Promise((rs, rj) => {
setTimeout(() => rs('mock data for ' + url), 100);
})
}));
}) as any;

it('fetches text from a URL and caches it so the next call is faster', async () => {
const tsBeforeCalls = Date.now();
const text1 = await fetchUrlCached('https://raw.githubusercontent.com/e-mission/e-mission-phone/master/README.md');
const tsBetweenCalls = Date.now();
const text2 = await fetchUrlCached('https://raw.githubusercontent.com/e-mission/e-mission-phone/master/README.md');
const tsAfterCalls = Date.now();
expect(text1).toEqual(expect.stringContaining('mock data'));
expect(text2).toEqual(expect.stringContaining('mock data'));
expect(tsAfterCalls - tsBetweenCalls).toBeLessThan(tsBetweenCalls - tsBeforeCalls);
});

/* The following functions from commHelper.ts are not tested because they are just wrappers
around the native functions in BEMServerComm.
If we wanted to test them, we would need to mock the native functions in BEMServerComm, but
this would be of limited value. It would be better to test the native functions directly.
* - getRawEntries
* - getPipelineRangeTs
* - getPipelineCompleteTs
* - getMetrics
* - getAggregateData
* - registerUser
* - updateUser
* - getUser
*/

0 comments on commit 77fe30a

Please sign in to comment.