mobx-utils icon indicating copy to clipboard operation
mobx-utils copied to clipboard

Testing stuff using now() leads to tests that are failing for wrong reason

Open jansav opened this issue 2 years ago • 0 comments

Multiple clocks with the same interval will automatically be synchronized.

The fact that timers are synchronized, will make multiple unit tests share state between them.

Here is unit test that will reproduce the issue:

Notice how latter test will fail, even though it shouldn't. If you run either of tests individually, the test will pass.

import { now } from "mobx-utils";
import { computed, observe } from "mobx";

describe("now", () => {
  let actual: boolean;

  beforeEach(() => {
    jest.useFakeTimers();

    jest.setSystemTime(new Date("2015-10-21T07:28:00Z"));

    const someComputed = computed(() => {
      const currentTimestamp = now(1000);

      return currentTimestamp > new Date("2015-10-21T07:28:00Z").getTime();
    });

    observe(someComputed, (changed) => {
      actual = changed.newValue as boolean;
    }, true);
  });

  it("given time passes, works", () => {
    jest.advanceTimersByTime(1000);

    expect(actual).toBe(true);
  });

  it("does not share the state from previous test", () => {
    expect(actual).toBe(false);
  });
})

And to be absolutely sure that synchronization is causing the trouble, you can comment out stuff from implementation of now to see that both unit tests will pass at same time when synchronization is disabled.

    function now(interval) {
      if (interval === void 0) { interval = 1000; }
        if (!mobx._isComputingDerivation()) {
            // See #40
            return Date.now();
        }
        // if (!tickers[interval]) {
            if (typeof interval === "number")
                return createIntervalTicker(interval).current(); // Notice return here
            else
                tickers[interval] = createAnimationFrameTicker();
        // }
        // return tickers[interval].current();
    }

I'd like to be able to disable the synchronization in unit tests.

jansav avatar Jul 01 '22 05:07 jansav