$ DEBUG_PRINT_LIMIT=0 jest --noStackTrace
https://jestjs.io/docs/en/mock-functions
There are two ways to mock functions: Either by:
jest.fn()
.mockReturnValue()
.mockReturnValueOnce()
.mockResolvedValue()
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()
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',
});
jest.mock('path/to/module', () => ({
__esModule: true,
default: 'value',
});
jest.clearAllMocks()
- clears out the calls and resultsjest.resetAllMocks()
- clear + remove mocked return valuesjest.restoreAllMocks()
- reset + restore original non-mocked functionshttps://krasimirtsonev.com/blog/article/jest-mock-console-methods
// silencing:
const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
// asserting
expect(warn).toHaveBeenCalledWith("HI")
// reverting
warn.mockReset();
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);
});
This can occur when an NPM dependency is shipped as ES6. Jest has not historically worked with ESM modules.
Options:
transformIgnorePatterns
- this config specifies what to ignore for Babel transformation. By default everything in node_modules
is ignored. To change that, specify that everything in node_modules
except certain subdirectories can be ignored: transformIgnorePatterns: ["node_modules/(?!@mui)/(?!x-charts)"],
--logHeapUsage
flag 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 issueworkerIdleMemoryLimit
config value (available in Jest 29) - https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring
testTimeout: [num]
https://jestjs.io/docs/configuration#testtimeout-numberit(name, testFn, timeout)