Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix now() sharing global state between tests #316

Merged
merged 3 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/now.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ const tickers: {
[interval: string]: IResource<number>
} = {}

export function clearTimers() {
for (const key in tickers) {
if (tickers.hasOwnProperty(key)) {
tickers[key].dispose()
delete tickers[key]
}
}
}

/**
* Returns the current date time as epoch number.
* The date time is read from an observable which is updated automatically after the given interval.
Expand Down Expand Up @@ -36,6 +45,7 @@ export function now(interval: number | "frame" = 1000) {
// See #40
return Date.now()
}

if (!tickers[interval]) {
if (typeof interval === "number") tickers[interval] = createIntervalTicker(interval)
else tickers[interval] = createAnimationFrameTicker()
Expand Down
37 changes: 37 additions & 0 deletions test/now.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,40 @@ test("now should be up to date when ticker is reactivated, #271", (done) => {
done()
}, 200)
})

describe("given desynchronization is enabled", () => {
let actual

beforeEach(() => {
jest.useFakeTimers("modern")
jest.setSystemTime(new Date("2015-10-21T07:28:00Z"))

const someComputed = mobx.computed(() => {
const currentTimestamp = utils.now(1000)

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

mobx.observe(
someComputed,
(changed) => {
actual = changed.newValue
},
true
)
})

afterEach(() => {
utils.clearTimers()
})

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)
})
})