sapegin/jest-cheat-sheet is a GitHub project with 5.4k stars in the Developer Tools space. Jest cheat sheet
Snapshot summary built from the project's own GitHub metadata — there's no written TopGit review yet. The page will update automatically when a full review is published.
WHY NO REVIEW YET
TopGit writes full reviews for the most-starred, most-requested repositories. This page is a snapshot until then — see the READ ME tab for the original README in full.
// Matches anything that an if statement treats as true (true, 1, 'hello', {}, [], 5.3)
expect('foo').toBeTruthy()
// Matches anything that an if statement treats as false (false, 0, '', null, undefined, NaN)
expect('').toBeFalsy()
// Matches only null
expect(null).toBeNull()
// Matches only undefined
expect(undefined).toBeUndefined()
// The opposite of toBeUndefined
expect(7).toBeDefined()
// Matches true or false
expect(true).toEqual(expect.any(Boolean))
// const fn = () => { throw new Error('Out of cheese!') }
expect(fn).toThrow()
expect(fn).toThrow('Out of cheese')
expect(fn).toThrowErrorMatchingSnapshot()
Aliases
toThrowError → toThrow
Snapshots
expect(node).toMatchSnapshot()
// Jest 23+
expect(user).toMatchSnapshot({
date: expect.any(Date),
})
expect(user).toMatchInlineSnapshot()
Mock functions
// const fn = jest.fn()
// const fn = jest.fn().mockName('Unicorn') -- named mock, Jest 22+
expect(fn).toBeCalled() // Function was called
expect(fn).not.toBeCalled() // Function was *not* called
expect(fn).toHaveBeenCalledTimes(1) // Function was called only once
expect(fn).toBeCalledWith(arg1, arg2) // Any of calls was with these arguments
expect(fn).toHaveBeenLastCalledWith(arg1, arg2) // Last call was with these arguments
expect(fn).toHaveBeenNthCalledWith(callNumber, args) // Nth call was with these arguments (Jest 23+)
expect(fn).toHaveReturnedTimes(2) // Function was returned without throwing an error (Jest 23+)
expect(fn).toHaveReturnedWith(value) // Function returned a value (Jest 23+)
expect(fn).toHaveLastReturnedWith(value) // Last function call returned a value (Jest 23+)
expect(fn).toHaveNthReturnedWith(value) // Nth function call returned a value (Jest 23+)
expect(fn.mock.calls).toEqual([
['first', 'call', 'args'],
['second', 'call', 'args'],
]) // Multiple calls
expect(fn.mock.calls[0][0]).toBe(2) // fn.mock.calls[0][0] — the first argument of the first call
It’s a good practice to specify a number of expected assertions in async tests, so the test will fail if your assertions weren’t called at all.
test('async test', () => {
expect.assertions(3) // Exactly three assertions are called during a test
// OR
expect.hasAssertions() // At least one assertion is called during a test
// Your async tests
})
You can also do this per file, outside any describe and test:
beforeEach(expect.hasAssertions)
This will verify the presence of at least one assertion per test case. It also plays nice with more specific expect.assertions(3) declarations.
In addition, you can enforce it globally, across all test files (instead of having to repeat per file) by adding the exact same line into one of the scripts referenced by the setupFilesAfterEnv configuration option. (For example, setupTests.ts and that is referenced via a setupFilesAfterEnv: ['<rootDir>/setupTests.ts'] entry in jest.config.ts.)
test('call the callback', () => {
const callback = jest.fn()
fn(callback)
expect(callback).toBeCalled()
expect(callback.mock.calls[0][1].baz).toBe('pizza') // Second argument of the first call
// Match the first and the last arguments but ignore the second argument
expect(callback).toHaveBeenLastCalledWith('meal', expect.anything(), 'margarita')
})
You can also use snapshots:
test('call the callback', () => {
const callback = jest.fn().mockName('Unicorn') // mockName is available in Jest 22+
fn(callback)
expect(callback).toMatchSnapshot()
// ->
// [MockFunction Unicorn] {
// "calls": Array [
// ...
})
jest.mock('lodash/memoize', () => (a) => a) // The original lodash/memoize should exist
jest.mock('lodash/memoize', () => (a) => a, { virtual: true }) // The original lodash/memoize isn’t required
jest.mock docs
[!NOTE]
When using babel-jest, calls to jest.mock will automatically be hoisted to the top of the code block. Use jest.doMock if you want to explicitly avoid this behavior.
Mock modules using a mock file
Create a file like __mocks__/lodash/memoize.js:
module.exports = (a) => a
Add to your test:
jest.mock('lodash/memoize')
[!NOTE]
When using babel-jest, calls to jest.mock will automatically be hoisted to the top of the code block. Use jest.doMock if you want to explicitly avoid this behavior.
fn.mockClear() // Clears mock usage date (fn.mock.calls, fn.mock.instances)
fn.mockReset() // Clears and removes any mocked return values or implementations
fn.mockRestore() // Resets and restores the initial implementation
[!NOTE]
The mockRestore works only with mocks created by jest.spyOn.
Write synchronous test for code that uses native timer functions (setTimeout, setInterval, clearTimeout, clearInterval).
// Enable fake timers
jest.useFakeTimers()
test('kill the time', () => {
const callback = jest.fn()
// Run some code that uses setTimeout or setInterval
const actual = someFunctionThatUseTimers(callback)
// Fast-forward until all timers have been executed
jest.runAllTimers()
// Check the results synchronously
expect(callback).toHaveBeenCalledTimes(1)
})
Or adjust timers by time with advanceTimersByTime():
// Enable fake timers
jest.useFakeTimers()
test('kill the time', () => {
const callback = jest.fn()
// Run some code that uses setTimeout or setInterval
const actual = someFunctionThatUseTimers(callback)
// Fast-forward for 250 ms
jest.advanceTimersByTime(250)
// Check the results synchronously
expect(callback).toHaveBeenCalledTimes(1)
})
Use jest.runOnlyPendingTimers() for special cases.
[!NOTE]
You should call jest.useFakeTimers() in your test case to use other fake timer methods.
Does sapegin/jest-cheat-sheet have a project website?
No homepage URL was recorded for sapegin/jest-cheat-sheet in TopGit's last sync. The README tab above frequently contains screenshots and demo links, or check the repository description on GitHub.
How does sapegin/jest-cheat-sheet compare to other Developer Tools projects?
sapegin/jest-cheat-sheet is tracked by TopGit in the Developer Tools category, with 5.4k GitHub stars. Browse the Developer Tools topic page on TopGit to compare it against similar projects by stars and activity.
How many stars does sapegin/jest-cheat-sheet have?
sapegin/jest-cheat-sheet has 5.4k GitHub stars — refresh the page for the live number, or check github.com/sapegin/jest-cheat-sheet. TopGit mirrors GitHub's count but does not claim minute-by-minute accuracy.
Is sapegin/jest-cheat-sheet open source?
Yes — sapegin/jest-cheat-sheet ships under the CC0-1.0 license, which makes its source code freely readable (and, depending on license terms, forkable and reusable). Source: github.com/sapegin/jest-cheat-sheet.
What else is in the Developer Tools space?
sapegin/jest-cheat-sheet is tracked by TopGit under the Developer Tools category, alongside 3 GitHub-tagged topics. Trending and Topics pages list peer repositories of comparable stars and language.
What is sapegin/jest-cheat-sheet?
sapegin/jest-cheat-sheet (sapegin/jest-cheat-sheet) is a multi-language project on GitHub. From the project's own README: Jest cheat sheet
Where do I read more about sapegin/jest-cheat-sheet?
This TopGit page is a snapshot — the READ ME tab shows the project's own README content (links stripped, images preserved). The GitHub repository at github.com/sapegin/jest-cheat-sheet is the definitive source.
Read full README in the tab above.
Is jest-cheat-sheet worth your time?
ChatGPT, Claude and Perplexity can all read this page. Ask one of them what it makes of jest-cheat-sheet.