Skip to content

Commit

Permalink
add shim and test
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinjude committed May 16, 2022
1 parent 6420b54 commit e55e787
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/gatsby-script/src/__tests__/gatsby-script.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,19 @@ const strategies: Array<ScriptStrategy> = [
ScriptStrategy.idle,
]

jest.mock(`../request-idle-callback-shim`, () => {
const originalModule = jest.requireActual(`../request-idle-callback-shim`)

return {
__esModule: true,
...originalModule,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
requestIdleCallback: jest.fn<any, any>(callback => callback()),
}
})

describe(`Script`, () => {
beforeAll(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
global.requestIdleCallback = jest.fn<any, any>(callback => callback())
// @ts-ignore Mock it out for now
performance.getEntriesByName = jest.fn(() => [])
})
Expand Down
18 changes: 18 additions & 0 deletions packages/gatsby-script/src/request-idle-callback-shim.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// https://developer.chrome.com/blog/using-requestidlecallback/#checking-for-requestidlecallback
// https://github.com/vercel/next.js/blob/canary/packages/next/client/request-idle-callback.ts

export const requestIdleCallback =
(typeof self !== `undefined` &&
self.requestIdleCallback &&
self.requestIdleCallback.bind(window)) ||
function (cb: IdleRequestCallback): number {
const start = Date.now()
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start))
},
})
}, 1) as unknown as number
}

0 comments on commit e55e787

Please sign in to comment.