diff --git a/packages/app-cli/tests/services_rest_Api.ts b/packages/app-cli/tests/services_rest_Api.ts index 6d74b1a6f1..34e9557a56 100644 --- a/packages/app-cli/tests/services_rest_Api.ts +++ b/packages/app-cli/tests/services_rest_Api.ts @@ -2,7 +2,7 @@ import { PaginationOrderDir } from '@joplin/lib/models/utils/types'; import Api, { RequestMethod } from '@joplin/lib/services/rest/Api'; import shim from '@joplin/lib/shim'; -const { setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, db } = require('./test-utils.js'); +const { setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, db, msleep } = require('./test-utils.js'); const Folder = require('@joplin/lib/models/Folder'); const Resource = require('@joplin/lib/models/Resource'); const Note = require('@joplin/lib/models/Note'); @@ -11,14 +11,6 @@ const NoteTag = require('@joplin/lib/models/NoteTag'); const ResourceService = require('@joplin/lib/services/ResourceService').default; const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); -async function msleep(ms: number) { - return new Promise((resolve) => { - shim.setTimeout(() => { - resolve(); - }, ms); - }); -} - const createFolderForPagination = async (num: number, time: number) => { await Folder.save({ title: `folder${num}`, diff --git a/packages/app-cli/tests/test-utils.ts b/packages/app-cli/tests/test-utils.ts index 11a98c1e0b..b7c4b390c5 100644 --- a/packages/app-cli/tests/test-utils.ts +++ b/packages/app-cli/tests/test-utils.ts @@ -203,9 +203,28 @@ function sleep(n: number) { } function msleep(ms: number) { + // It seems setTimeout can sometimes last less time than the provided + // interval: + // + // https://stackoverflow.com/a/50912029/561309 + // + // This can cause issues in tests where we expect the actual duration to be + // the same as the provided interval or more, but not less. So the code + // below check that the elapsed time is no less than the provided interval, + // and if it is, it waits a bit longer. + const startTime = Date.now(); return new Promise((resolve) => { shim.setTimeout(() => { - resolve(null); + if (Date.now() - startTime < ms) { + const iid = setInterval(() => { + if (Date.now() - startTime >= ms) { + clearInterval(iid); + resolve(null); + } + }, 2); + } else { + resolve(null); + } }, ms); }); }