The purpose of the tests is to mock parallel requests that fetch different sources of data. I introduce an artificial latency for each request and after some time return a simple string with an identifying digit to see if the data has been loaded from cache (requests within 500ms) or not. So for data loaded within 500ms the output should be "A1B1", else, after 500ms, it should be "A2B2" and so on.
// index.test.js
const { wait } = require('./util/wait.js');
const { requestAandB, requestBandC } = require('./index.js');
test('Test cache timings ', () => Promise.all([
// send two requests in parallel after 0 ms (immediately)
wait(0).then(() => Promise.all([
expect(requestAandB()).resolves.toEqual('A1B1'),
expect(requestBandC()).resolves.toEqual('B1C1'),
])),
// send two requests in parallel after 480 ms
wait(480).then(() => Promise.all([
expect(requestAandB()).resolves.toEqual('A1B1'),
expect(requestBandC()).resolves.toEqual('B1C1'),
])),
// send two requests in parallel after 520 ms
wait(520).then(() => Promise.all([
expect(requestAandB()).resolves.toEqual('A2B2'),
expect(requestBandC()).resolves.toEqual('B2C2'),
])),
]));
This is how I mock the data loads
// get-data.js
async function mockLoading(str) {
// introduce some latency
const waitDuration = Math.round(Math.random() * (WAIT_MAX - WAIT_MIN)) + WAIT_MIN;
await wait(waitDuration);
// create or increase counter every time the function is being called
counters[str] = counters[str] === undefined ? 1 : counters[str] + 1;
return str + counters[str];
}
module.exports = {
loadDataA: async () => mockLoading('A'),
loadDataB: async () => mockLoading('B'),
loadDataC: async () => mockLoading('C'),
}
Finally, the implementation for the methods requestAandB and requestBandC imported in the test file:
const { loadDataA, loadDataB, loadDataC } = require('./model/get-data.js');
const all = Promise.all([loadDataA(), loadDataB(), loadDataC()])
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function requestAandB() {
const temp = await all
await delay(Math.random() * 510)
return temp.filter((_, i) => i < 2).join("")
}
async function requestBandC() {
const temp = await all
await delay(Math.random() * 510)
return temp.filter((_, i) => i > 0).join("")
}
module.exports = { requestAandB, requestBandC }
Tests for the data "A1B1", "B1C1" are fine, but because the latency (in the mockLoading function) is always above the 500ms threshold, I am not able to get the right results for data returned after that. In effect, "A2B2" and "B2C2" always fail.
Does anyone know what am I missing here?
from How to test parallel, mocked data requests in JEST whilst simulating cached responses with a 500ms threshold
No comments:
Post a Comment