{"id":22076485,"url":"https://github.com/codecademy/jest-globals","last_synced_at":"2025-07-24T13:30:57.658Z","repository":{"id":46494689,"uuid":"413448671","full_name":"Codecademy/jest-globals","owner":"Codecademy","description":"Mocks out global variables with Jest spies.","archived":false,"fork":false,"pushed_at":"2022-04-05T11:42:06.000Z","size":138,"stargazers_count":3,"open_issues_count":1,"forks_count":0,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-07-18T06:52:17.487Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Codecademy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-10-04T14:07:11.000Z","updated_at":"2023-01-07T07:03:29.000Z","dependencies_parsed_at":"2022-09-26T18:01:22.636Z","dependency_job_id":null,"html_url":"https://github.com/Codecademy/jest-globals","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Codecademy/jest-globals","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Codecademy%2Fjest-globals","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Codecademy%2Fjest-globals/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Codecademy%2Fjest-globals/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Codecademy%2Fjest-globals/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Codecademy","download_url":"https://codeload.github.com/Codecademy/jest-globals/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Codecademy%2Fjest-globals/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266850142,"owners_count":23995008,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-24T02:00:09.469Z","response_time":99,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-30T22:14:49.900Z","updated_at":"2025-07-24T13:30:57.369Z","avatar_url":"https://github.com/Codecademy.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🎭 jest-globals\n\n[![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-brightgreen.svg)](https://prettier.io)\n![TypeScript: Strict](https://img.shields.io/badge/typescript-strict-brightgreen.svg)\n[![NPM version](https://badge.fury.io/js/jest-globals.svg)](http://badge.fury.io/js/jest-globals)\n[![Join the chat at https://gitter.im/Codecademy/jest-globals](https://badges.gitter.im/Codecademy/jest-globals.svg)](https://gitter.im/Codecademy/jest-globals?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n\nMocks out global variables with Jest spies.\n\n## Usage\n\n`jest-globals` sets up a collection of global mocks such as `location` and `navigator` and assigns them to global variables on `globalThis`.\nIf a `typeof window !== undefined` then it will assign the same values to `window` as well.\n\nYour source code can then still refer to global variables normally...\n\n```ts\n// Source file: ./example.ts\nexport function example() {\n  window.location.assign(\"/path\");\n}\n```\n\n...and your test files can import and use their test versions, as long as `jest-globals` is imported before the code under test:\n\n```ts\n// Test file: ./example.test.ts\nimport { location } from \"jest-globals\";\nimport { example } from \"./example\";\n\ndescribe(\"example\", () =\u003e {\n  it(\"assigns /path to location\", () =\u003e {\n    example();\n    expect(location.assign).toHaveBeenCalledWith(\"/path\");\n  });\n});\n```\n\n\u003e See [#Custom Usage](#custom-usage) below for more details.\n\n### Available Globals\n\nFor each global available, you can `import` it from `jest-globals` directly.\n\n#### `addEventListener`\n\n```ts\nimport { addEventListener } from \"jest-globals\";\n\nexpect(addEventListener).toHaveBeenCalledWith(\"load\", expect.any(Function));\n```\n\n#### `alert`\n\n```ts\nimport { alert } from \"jest-globals\";\n\nexpect(alert).toHaveBeenCalledWith(expect.any(Function));\n```\n\n#### `blur`\n\n```ts\nimport { blur } from \"jest-globals\";\n\nexpect(blur).toHaveBeenCalledTimes(1);\n```\n\n#### `close`\n\n```ts\nimport { close } from \"jest-globals\";\n\nexpect(close).toHaveBeenCalledTimes(1);\n```\n\n#### `confirm`\n\n```ts\nimport { confirm } from \"jest-globals\";\n\nexpect(confirm).toHaveBeenCalledTimes(1);\n```\n\n#### `dispatchEvent`\n\n```ts\nimport { dispatchEvent } from \"jest-globals\";\n\nexpect(dispatchEvent).toHaveBeenCalledTimes(1);\n```\n\n#### `focus`\n\n```ts\nimport { focus } from \"jest-globals\";\n\nexpect(focus).toHaveBeenCalledTimes(1);\n```\n\n#### `getSelection`\n\nUse `createMockSelection` to create a valid `Selection` with stub data for any field not explicitly provided.\n\n```ts\nimport { createMockSelection, getSelection } from \"jest-globals\";\n\ngetSelection.mockReturnValue(\n  createMockSelection({\n    focusOffset: 2,\n  })\n);\n```\n\n#### `localStorage`\n\n`localStorage` is assigned an instance of a `MockStorage` class of assigned items under an `items` `Map`.\n\n```ts\nimport { localStorage } from \"jest-globals\";\n\nlocalStorage.setItem(\"powerLevel\", \"9001\");\n\nexpect(localStorage.setItem).toHaveBeenCalledWith(\"powerLevel\", \"9001\");\nexpect(localStorage.items.getItem(\"powerLevel\")).toEqual(\"9001\");\n```\n\n\u003e `MockStorage`'s `constructor` includes a `beforeEach(() =\u003e this.items.clear())`.\n\n#### `location`\n\n```ts\nimport { location } from \"jest-globals\";\n\nexpect(location.assign).toHaveBeenCalledWith(\"/path\");\n```\n\n#### `matchMedia`\n\n```ts\nimport { createMockMediaQueryList, matchMedia } from \"jest-globals\";\n\nmatchMedia.mockReturnValue(\n  createMockMediaQueryList({\n    //\n  })\n);\n```\n\n#### `moveBy`\n\n```ts\nimport { moveBy } from \"jest-globals\";\n\nexpect(moveBy).toHaveBeenCalledWith(12, 34);\n```\n\n#### `navigator`\n\n```ts\nimport { navigator } from \"jest-globals\";\n\nnavigator.mockUserAgent.mockReturnValue(\"Mozilla/123\");\nnavigator.clipboard.readText.mockResolvedValue(\"It's over 9,000!\");\nexpect(navigator.serviceWorker.register).toHaveBeenCalled();\n```\n\n#### `open`\n\n```ts\nimport { open } from \"jest-globals\";\n\nexpect(open).toHaveBeenCalledWith(\"https://hi.joshuakgoldberg.com\");\n```\n\n#### `performance`\n\n```ts\nimport { performance } from \"jest-globals\";\n\nperformance.now.mockReturnValue(9001);\n```\n\n#### `postMessage`\n\n```ts\nimport { postMessage } from \"jest-globals\";\n\nexpect(postMessage).toHaveBeenCalledWith(\"Is anybody out there?\", \"*\");\n```\n\n#### `print`\n\n```ts\nimport { print } from \"jest-globals\";\n\nexpect(print).toHaveBeenCalledTimes(1);\n```\n\n#### `prompt`\n\n```ts\nimport { prompt } from \"jest-globals\";\n\nexpect(prompt).toHaveBeenCalledWith(\"Hello my baby\");\n```\n\n#### `removeEventListener`\n\n```ts\nimport { removeEventListener } from \"jest-globals\";\n\nexpect(removeEventListener).toHaveBeenCalledWith(expect.any(Function));\n```\n\n#### `requestAnimationFrame`\n\n```ts\nimport { requestAnimationFrame } from \"jest-globals\";\n\nexpect(requestAnimationFrame).toHaveBeenCalledWith(expect.any(Function));\n```\n\n#### `requestIdleCallback`\n\n```ts\nimport { requestIdleCallback } from \"jest-globals\";\n\nexpect(requestIdleCallback).toHaveBeenCalledWith(expect.any(Function));\n```\n\n#### `resizeBy`\n\n```ts\nimport { resizeBy } from \"jest-globals\";\n\nexpect(resizeBy).toHaveBeenCalledWith(12, 34);\n```\n\n#### `resizeTo`\n\n```ts\nimport { resizeTo } from \"jest-globals\";\n\nexpect(resizeTo).toHaveBeenCalledWith(123, 456);\n```\n\n#### `scrollBy`\n\n```ts\nimport { scrollBy } from \"jest-globals\";\n\nexpect(scrollBy).toHaveBeenCalledWith(12, 34);\n```\n\n#### `scrollTo`\n\n```ts\nimport { scrollTo } from \"jest-globals\";\n\nexpect(scrollTo).toHaveBeenCalledWith(123, 456);\n```\n\n#### `sessionStorage`\n\n`sessionStorage` is assigned an instance of a `MockStorage` class that keeps track of assigned items under an `items` member of type `Map\u003cstring, string\u003e`:\n\n```ts\nimport { sessionStorage } from \"jest-globals\";\n\nsessionStorage.setItem(\"powerLevel\", \"9001\");\n\nexpect(sessionStorage.setItem).toHaveBeenCalledWith(\"powerLevel\", \"9001\");\nexpect(sessionStorage.items.getItem(\"powerLevel\")).toEqual(\"9001\");\n```\n\n\u003e `MockStorage`'s `constructor` includes a `beforeEach(() =\u003e this.items.clear())`.\n\n#### `setImmediate`\n\n```ts\nimport { setImmediate } from \"jest-globals\";\n\nexpect(setImmediate).toHaveBeenCalledWith(expect.any(Function));\n```\n\n#### `stop`\n\n```ts\nimport { stop } from \"jest-globals\";\n\nexpect(stop).toHaveBeenCalledTimes(1);\n```\n\n#### `top`\n\n`window.top` is by default a reference to an identical mock window object, except its `.top` references itself.\n\n```ts\nimport { top } from \"jest-globals\";\n\nexpect(top.postMessage).toHaveBeenCalledWith(\"I'll be back one day\", \"*\");\n```\n\n### Strongly Typed Usage\n\n`jest-globals` is written in TypeScript and generally type safe.\nImported objects from `jest-globals` are typed as having `jest.Mock`s for their functions with parameters and return types corresponding to their original mocks.\n\nGlobal mocks that return complex original objects therefore require `mockReturnValue` and co. to be provided with objects that match up to the original type:\n\n```ts\nimport { getSelection } from \"jest-globals\";\n\ngetSelection.mockReturnValue({\n  focusOffset: 2,\n});\n// Error: Argument of type '{ focusOffset: number; }' is not assignable to parameter of type 'Selection'.\n//   Type '{ focusOffset: number; }' is missing the following properties from type 'Selection': anchorNode, anchorOffset, focusNode, focusOffset, and 16 more.\n```\n\nEach of these APIs has a corresponding `createMock*` function exported by `jest-globals` that takes in a `Partial` of the returned type and fills in any missing fields:\n\n```ts\nimport { createMockSelection, getSelection } from \"jest-globals\";\n\ngetSelection.mockReturnValue(\n  createMockSelection({\n    focusOffset: 2,\n  })\n);\n```\n\n### What's Not Provided\n\nThe following global members are complex enough that they warrant their own dedicated packages:\n\n- `document`: [`jest-environment-jsdom`](https://www.npmjs.com/package/jest-environment-jsdom)\n- `fetch`: [`fetch-mock`](https://www.npmjs.com/package/fetch-mock) / [`fetch-mock-jest`](https://www.npmjs.com/package/fetch-mock-jest)\n- `getComputedStyle`: similar to `document`\n- `XMLHTTPRequest`: use `fetch` instead 😄\n\n## Custom Usage\n\n### Auto-Sorted Involvement\n\nIf you'd like `jest-globals` to run after library code, it may be inconvenient to also have a linter plugin thatt auto-sorts your imports.\n\n```ts\n// example.test.js\nimport \"jest-globals\"; // runs first 😔\nimport userEvent from \"@testing-library/user-event\";\n```\n\nIf your configuration puts imports under a prefix such as `~/` last, you can create a file whose sole purpose is to import `jest-globals`:\n\n```ts\n// tests/globals\nexport * from \"jest-globals\";\n```\n\n```ts\n// example.test.js\nimport userEvent from \"@testing-library/user-event\";\nimport \"~/tests/globals\"; // runs last 😌\n```\n\nAnother (less type safe) workaround is to use Jest's [`moduleNameMapper`](https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring) to allow importing under a name like `zzzest-globals`, pushing it alphabetically below other absolute imports:\n\n```json\n{\n  \"moduleNameMapper\": {\n    \"^zzzest-globals$\": \"jest-globals\"\n  }\n}\n```\n\n```ts\n// example.test.js\nimport userEvent from \"@testing-library/user-event\";\nimport \"zzzest-globals\"; // runs last 😌\n```\n\n### Permanent Involvement\n\nIf you'd like `jest-globals` to _always_ be run before all your files, you can include it in your [`setupFilesAfterEnv`](https://jestjs.io/docs/configuration#setupfilesafterenv-array):\n\n```js\n// ./jest.setup.js\nrequire(\"jest-globals\");\n```\n\n## Development\n\nRequires:\n\n- [Node.js](https://nodejs.org) \u003e14\n- [Yarn](https://yarnpkg.com/en)\n\nAfter [forking the repo from GitHub](https://help.github.com/articles/fork-a-repo):\n\n```\ngit clone https://github.com/\u003cyour-name-here\u003e/jest-globals\ncd jest-globals\nyarn\n```\n\n### Contribution Guidelines\n\nWe'd love to have you contribute!\nCheck the [issue tracker](https://github.com/Codecademy/jest-globals/issues) for issues labeled [`accepting prs`](https://github.com/Codecademy/jest-globals/issues?utf8=%E2%9C%93\u0026q=is%3Aissue+is%3Aopen+label%3A%22accepting+prs%22) to find bug fixes and feature requests the community can work on.\nIf this is your first time working with this code, the [`good first issue`](https://github.com/Codecademy/jest-globals/issues?utf8=%E2%9C%93\u0026q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22+) label indicates good introductory issues.\n\nPlease note that this project is released with a [Contributor Covenant](https://www.contributor-covenant.org).\nBy participating in this project you agree to abide by its terms.\nSee [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodecademy%2Fjest-globals","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodecademy%2Fjest-globals","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodecademy%2Fjest-globals/lists"}