Jest call arg is a set of utility functions to call callbacks passed to mocked functions. This is handy for testing code that deals with mocked functions that take callbacks. It is partly inspired by sinon's callArg fucntionality.
npm install jest-call-arg --save-dev
Import in the test file you want to use it:
CommonJS:
const { callArg, callArgWith } = require("jest-call-arg");
ES6 Modules
import { callArg, callArgWith } from "jest-call-arg";
Calls the callback argument at the given position (default is 0);
const mockFn = jest.fn();
const callback = jest.fn();
mockFn("test", callback);
callArg(mockFn, 1);
expect(callback).toHaveBeenCalled(); // Passes
Same as callArg
but with optional arguments to pass to the callback.
const mockFn = jest.fn();
const callback = jest.fn();
mockFn(callback);
callArgWith(mockFn, 0, "Hello world");
expect(callback).toHaveBeenCalledWith("Hello world"); // Passes
Same as callArgWith
but with the ability to override the this
context for the callback.
When the argument at position 0 matches the event name, calls the callback argument at position 1.
const mockedElement = { addEventListener: jest.fn() };
const callback = jest.fn();
mockedElement.addEventListener("click", callback);
mockedElement.addEventListener("change", callback);
callEventHandler(mockedElement.addEventListener, "click");
expect(callback).toHaveBeenCalledTimes(1); // Passes
Same as callEventHandler
but then with the ability to pass arguments to the callback.