Skip to content
This repository has been archived by the owner on Apr 18, 2022. It is now read-only.

Potential bug in FakeTime.restoreFor #9

Closed
meooow25 opened this issue Apr 10, 2021 · 2 comments
Closed

Potential bug in FakeTime.restoreFor #9

meooow25 opened this issue Apr 10, 2021 · 2 comments

Comments

@meooow25
Copy link

It is possible for previously queued code to execute between the restore and override steps in restoreFor, which means they unexpectedly use the native time functions.

mock/time.ts

Lines 337 to 342 in cf21e99

time.restoreGlobals();
try {
result = await callback.apply(null, args);
} finally {
time.overrideGlobals();
}

I found this when using delay (which in turn uses restoreFor).

import { FakeTime, NativeTime, delay } from "https://deno.land/x/mock@v0.9.4/time.ts";

function isNative(prefix) {
  console.log(prefix, setTimeout === NativeTime.setTimeout ? "native" : "not native");
}

async function fun() {
  await Promise.resolve();
  // I expect setTimeout to be fake here but it is not
  isNative("fun");
}

const ft = new FakeTime();
isNative("before");
fun();
await delay(0);
isNative("after");

// outputs:
// before not native
// fun native
// after not native
@KyleJune
Copy link
Member

fun is asynchronous. Without awaiting it before calling the delay function that restores native time, there is a chance that native time would be restored temporarily while the code in fun is running. You could encounter a similar issue if you were to call ft.restore() after fun without awaiting it.

@meooow25
Copy link
Author

I realize how it works, but my intent was to point out that someone using the library may not immediately figure out that delay/restoreFor has such a side effect. Whether this needs a fix, the choice is yours.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants