Skip to content

Instantly share code, notes, and snippets.

@AshCoolman
Forked from vojty/jest.md
Created January 25, 2018 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshCoolman/fb3be238fb4b9e06c137cef25b12df8b to your computer and use it in GitHub Desktop.
Save AshCoolman/fb3be238fb4b9e06c137cef25b12df8b to your computer and use it in GitHub Desktop.
Jest cheat sheet

Jest cheat shiiiit

Expect

expect.any(constructor) // expect(callback).toBe(expect.any(Function))
expect.assertions(number) // total count of expected assertions, useful for async tests
.not
.resolves
.rejects
.toBe(value)
.toHaveBeenCalled()
.toHaveBeenCalledTimes(number)
.toHaveBeenCalledWith(arg1, arg2, ...)
.toHaveBeenLastCalledWith(arg1, arg2, ...)
.toBeCloseTo(number, numDigits)
.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(number)
.toBeGreaterThanOrEqual(number)
.toBeLessThan(number)
.toBeLessThanOrEqual(number)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toHaveLength(number)
.toMatch(regexpOrString)
.toMatchObject(object)
.toHaveProperty(keyPath, value)
.toMatchSnapshot(optionalString)
.toThrow(error)
.toThrowErrorMatchingSnapshot()

Jest object

Standard spy

const callback = jest.fn(() => "mock return value"); // function is optional
callback(1);
callback(2);
expect(callback).toHaveBeenCalledTimes(2);
expect(callback.mock.calls[callIndex][argIndex]).toEqual(...);

Spy on object method

const spy = jest.spyOn(object, 'objectMethod');
object.objectMethod();
expect(spy).toHaveBeenCalled();

spy.mockReset(); // resets spy
spy.mockRestore(); // resets original method IMPORTANT for cleanup eg. mocking window

Spy and override method

jest.spyOn(object, 'methodName').mockImplementation(() => 'my value');
jest.spyOn(object, 'methodName')
    .mockImplementationOnce(() => 'first call')
    .mockImplementationOnce(() => 'second call'); // can be called on jest.fn() too

Timers

jest.useFakeTimers();
jest.runTimersToTime(500); // ms
jest.clearAllTimers();

Jest object API

jest.clearAllTimers()
jest.isMockFunction(fn)
jest.genMockFromModule(moduleName)
jest.mock(moduleName, factory, options)
jest.clearAllMocks()
jest.resetAllMocks()
jest.resetModules()
jest.runAllTicks()
jest.runAllTimers()
jest.runTimersToTime(msToRun)
jest.runOnlyPendingTimers()
jest.setMock(moduleName, moduleExports)
jest.unmock(moduleName)
jest.useFakeTimers()
jest.useRealTimers()

Configuration

Polyfills

Request animation frame

yarn add --dev raf

// jest.setup.js
const raf = require('raf');
raf.polyfill();

// package.json
"jest": {
    ...
    "setupTestFrameworkScriptFile": "<rootDir>/jest.setup.js",
    ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment