https://github.com/ngerritsen/jest-call-arg
Utilitiy functions for calling callbacks on mocked functions with jest.
https://github.com/ngerritsen/jest-call-arg
callbacks javascript jest testing testing-tools
Last synced: 5 months ago
JSON representation
Utilitiy functions for calling callbacks on mocked functions with jest.
- Host: GitHub
- URL: https://github.com/ngerritsen/jest-call-arg
- Owner: ngerritsen
- Created: 2018-07-06T20:46:47.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2024-10-10T20:18:05.000Z (over 1 year ago)
- Last Synced: 2025-10-05T04:13:12.394Z (9 months ago)
- Topics: callbacks, javascript, jest, testing, testing-tools
- Language: JavaScript
- Homepage:
- Size: 63.5 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Jest call arg
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.
### Installation
`npm install jest-call-arg --save-dev`
### Usage
Import in the test file you want to use it:
CommonJS:
```js
const { callArg, callArgWith } = require("jest-call-arg");
```
ES6 Modules
```js
import { callArg, callArgWith } from "jest-call-arg";
```
### `callArg(mockFn, [position=0])`
Calls the callback argument at the given position (default is 0);
```js
const mockFn = jest.fn();
const callback = jest.fn();
mockFn("test", callback);
callArg(mockFn, 1);
expect(callback).toHaveBeenCalled(); // Passes
```
### `callArgWith(mockFn, [position=0], [arg1, arg2, ...])`
Same as `callArg` but with optional arguments to pass to the callback.
```js
const mockFn = jest.fn();
const callback = jest.fn();
mockFn(callback);
callArgWith(mockFn, 0, "Hello world");
expect(callback).toHaveBeenCalledWith("Hello world"); // Passes
```
### `callArgOnWith(mockFn, [position=0], context, [arg1, arg2, ...])`
Same as `callArgWith` but with the ability to override the `this` context for the callback.
### `callEventHandler(mockFn, [eventName])`
When the argument at position 0 matches the event name, calls the callback argument at position 1.
```js
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
```
### `callEventHandlerWith(mockFn, [eventName], [arg1, arg2, ....])`
Same as `callEventHandler` but then with the ability to pass arguments to the callback.