Jest
Shortening Output
$ DEBUG_PRINT_LIMIT=0 jest --noStackTrace
Mock Functions
https://jestjs.io/docs/en/mock-functions
There are two ways to mock functions: Either by:
- creating a mock function to use in test code, or
- writing a manual mock to override a module dependency.
- Using a mock function
- It's standalone and can be passed around
jest.fn()
.mockReturnValue()
.mockReturnValueOnce()
.mockResolvedValue()
- Mocking modules
import thing from 'thing'; // first do a real import of the whole module
jest.mock('thing'); // then mock it
thing.function.mockReturnValue(); // then properties on it are mocks and can be interacted with
What you can do with a mock:
.mockReturnValue()
.mockReturnValueOnce()
.mockResolvedValue()
.mockImplementation(fn)
.mockReturnThis() - for chaining
Helpful for output:
.mockName('thingName')
Matching on mocks
[.not]
.toBeCalled()
.toBeCalledWith()
Mocking Modules
https://jestjs.io/docs/mock-functions#mocking-modules
import something from 'path/to/module';
jest.mock('path/to/module');
jest.mock('path/to/module', () => ({
namedExport: 'value',
});
ES6 Default Export
jest.mock('path/to/module', () => ({
__esModule: true,
default: 'value',
});
Shared Mocks
jest.clearAllMocks()- clears out the calls and resultsjest.resetAllMocks()- clear + remove mocked return valuesjest.restoreAllMocks()- reset + restore original non-mocked functions
Mocking Console
https://krasimirtsonev.com/blog/article/jest-mock-console-methods
// silencing:
const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
// asserting
expect(warn).toHaveBeenCalledWith("HI")
// reverting
warn.mockReset();
Table-Based Tests
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
SyntaxError: Cannot use import statement outside a module
This can occur when an NPM dependency is shipped as ES6. Jest has not historically worked with ESM modules.
Options:
- Use native Jest ESM support. It is experimental, and it hasn't fixed the issue I was experiencing; unclear why. Could just be a misconfigured third-party package.
transformIgnorePatterns- this config specifies what to ignore for Babel transformation. By default everything innode_modulesis ignored. To change that, specify that everything innode_modulesexcept certain subdirectories can be ignored:transformIgnorePatterns: ["node_modules/(?!@mui)/(?!x-charts)"],
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
- How to diagnose it: pass the
--logHeapUsageflag and Jest will show the heap size after each test completes. If it’s 2+ GB and generally increasing over the test suite run, there is probably an issue - Root cause: a memory leak from Node 16.11.0 until 21.1.0. https://github.com/jestjs/jest/issues/11956
- Fixes:
- Upgrade to a version of Node with the fix (I’m not sure which these are)
- Downgrade to Node 16.10.0, which does not have the bug
- In an affected version of Node, set the
workerIdleMemoryLimitconfig value (available in Jest 29) - https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring- "512MB" or "1GB" are good starting values
- References
Timeout
- Suite-wide:
testTimeout: [num]https://jestjs.io/docs/configuration#testtimeout-number - Per-test:
it(name, testFn, timeout)
Slapdash