-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathjest.node_cli.txt
463 lines (383 loc) · 27.4 KB
/
jest.node_cli.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
┏━━━━━━━━━━┓
┃ JEST ┃
┗━━━━━━━━━━┛
ALTERNATIVES ==> #See Mocha
VERSION ==> #30.0.0-alpha.7
#Monorepository
JASMINE ==> #Used to be used as the base but not anymore
ASSERTIONS ==> #See Jest assertions doc
DIFF TESTING ==> #See Jest snapshots doc
REPORTERS ==> #See Jest reporters doc
DATA-DRIVEN TESTING ==> #See Jest data-driven doc
GENERIC MOCKING ==> #See Jest mocks doc
DEPENDENCIES MOCKING ==> #See Jest modules doc
TIMERS MOCKING ==> #See Jest timers doc
TEST COVERAGE ==> #See Istanbul doc
┌───────────┐
│ TESTS │
└───────────┘
describe(STR, FUNC()) #Test suite.
#Can be nested.
it|test(STR, FUNC([FUNC2])) #Test case.
#Async if:
# - FUNC2 defined
# - PROMISE returned
#Fails if:
# - error thrown
# - calling FUNC2(ERROR)
# - calling [FUNC2.]fail(STR|ERROR) (better stack trace)
# - returned PROMISE is rejected
#FUNC can be FUNC* (generator)
CONF.injectGlobals #If false (def: true), global variables (describe|it|test|beforeEach|...) must be imported
#from '@jest/globals' or import.meta.jest instead.
┌───────────────────┐
│ ORCHESTRATION │
└───────────────────┘
before|afterAll|Each(FUNC([FNC2]))#Fire FUNC() before|after once|each in current describe() (or all if outside)
#Since each top-level test file is isolated for each other,
#this is only for current top-level test file (and the files required by it).
CONF.setupFiles #Files RPATH_ARR required before any test file (like beforeAll())
#Can optionally export a FUNC()->>
CONF.setupFilesAfterEnv
--setupFilesAfterEnv #Same except single RPATH and run after CONF.setupFiles
CONF.globalSetup|Teardown #RPATH to a FUNC([FUNC2, CONF]) executed once before all test files
this #Top-level `this` is an empty object
#describe|it() `this` is not shared
#I.e. can either:
# - use arrow functions and reuse that `this` object
# - not use `this` but share a top-level object
┌────────────┐
│ CONFIG │
└────────────┘
CONF #In:
# - jest -c|--config=CONFIG_FILE.js|json|cjs|mjs|ts|cts
# - ./jest.config.js|cjs|mjs|ts
# - exporting an [PROMISE_]OBJ[()]
# - package.json: PACKAGE.jest CONF_OBJ or 'PATH' to CONFIG_FILE
#JSON can have comments
--showConfig #Prints resolved CONF then exits
--debug #Prints resolved CONF then run tests
--init #Generate sample config file
CONF.preset #'MODULE' exporting a CONF (jest-preset.js|json) to use as base config
CONF.projects #CONF_ARR. Run several instances of Jest at once, each with different CONF
--projects 'DIR'... #Can also be 'DIR'_ARR as shortcut for { roots: ['DIR'] }...
--ignoreProjects 'DIR'... #
--selectProjects 'STR'... #Same using CONF.displayName
jest DIR... #Each CONF should have displayName STR property (used as title)
--errorOnDeprecated #Errors on deprecated Jest APIs
┌───────────────┐
│ SELECTION │
└───────────────┘
describe|it|test.skip(...) #Skip this
xdescribe|it|test(...) #Can also omit FUNC
pending([STR]) #Same, inside a test
describe|it|test.only(...)
fdescribe|it|test(...) #Only run this
it|test.failing(...) #Expect tests to fail
CONF.testMatch #'GLOB'_ARR (using micromatch) of test files to include
#Def: any *.spec|test.EXT or __tests__/**/*.EXT
#Where EXT is js|cjs|mjs|jsx|ts|mts|cts|tsx
jest REGEXP
CONF.testRegex
--testPathPatterns=REGEXP #Kindof same thing
CONF.testPathIgnorePatterns
--testPathIgnorePatterns=REGEXP #'REGEXP'_ARR (def: ['/node_modules/']) of test files to ignore
--runTestsByPath #Do not run test files selected by REGEXPs
CONF.rootDir #Base 'DIR' (def: package.json DIR, or $PWD)
#Can also use '<rootDir>' in other CONF.*
--roots
CONF.roots #'DIR'_ARR (def: ['<rootDir>']) where source files, test files and __mock__ files are searched
-o #Only run test files that have changed or whose required files have changed
--onlyChanged #Does not work with dynamic requires
#"Changed" is any file modified since last commit, from a Git/Mercurial perspective
--lastCommit #Same but files modified by last commit (not ones currently modified)
--changedFilesWithAncestor #Same as --onlyChanged --lastCommit
--changedSince BRANCH #Same but files modifies since BRANCH's commit
--findRelatedTests FILE,... #Same but with explicit list of files
--filter=MODULE #Use custom filtering logic
#Not documented yet
--listTests #Show list of test files that will be run
--outputFile=FILE #With --listTests
-t REGEXP
--testNamePattern REGEXP #Only run tests whose title matches REGEXP
--extensionsToTreatAsEsm
'.EXT'_ARR #Def: ['.js', '.mjs']
┌───────────────┐
│ EXECUTION │
└───────────────┘
-b
--bail
CONF.bail #BOOL (def: false) or NUM. Stops running tests after NUM (1 if true) test failures.
--onlyFailures|-f #BOOL (def: false). Only run tests that previously failed
--forceExit #Call process.exit() after test run, even if there are some pending macrotasks
--detectOpenHandles #Prints remaining pending macrotasks at end of test run
#Based on ASYNC_HOOKS, i.e. slow
#Imply --runInBand
--passWithNoTests #Make testing succeed (instead of fail) when there are no tests
JEST.retryTimes(NUM[, OPTS])->JEST#Retry failing tests NUM times
OPTS.logErrorsBeforeRetry #BOOL (def: false). Log on retry
OPTS.retryImmediately #BOOL. If false (def), wait for other tests to finish before retrying
OPTS.waitBeforeRetry #NUM (def: 0, in ms) to wait between retries
--watch #Watch mode: re-run on files changes (uses watchman)
#Only re-run impacted test files.
#Has interactive mode, allowing to:
# - re-run with --onlyChanged, --testPathPattern, --testNamePattern or only failed tests
# - update snapshots
--watchAll #Same but re-run all test files, not just impacted ones.
--no-watchman #Same but does not watch for new files.
CONF.watchPathIgnorePatterns #'REGEXP'_ARR of files that should not trigger new run in watch mode
CONF.watchPlugins #ARR of 'MODULE'|MODULE_OBJ of plugins to customize watch mode.
#See online doc for how to customize.
jest-watch-typeahead ##Watch plugin to allow filtering which test is watched by names regexp
jest-watch-select-projects ##Watch plugin to allow filtering which test is watched by CONF.projects
CONF.dependencyExtractor #'MODULE' to customize how dependencies are guessed from files (e.g. used by watch mode).
#See online doc for how to customize.
CONF.runner #RPATH. Main action performed by Jest.
#By default is "jest-runner", i.e. perform tests with Jest.
#But can do other things:
# - so Jest is used as a test framework instead of a test runner
# - i.e. re-use watch mode, reporting, parallelism, selection, execution, but not core test running
#I think using a build automation tool (Gulp, etc.) is better for this.
#Available ones (see their doc online):
# - jest-runner-eslint: ESLint
# - jest-runner-mocha: Mocha
# - jest-runner-tsc: TypeScript compiling
# - jest-runner-prettier: Prettier
CREATE-JEST-RUNNER ==> ##Library helping creating custom runners
--testRunner RPATH #Core test running engine
CONF.testRunner RPATH #Def: 'jest-circus/runner'
--shard=NUM/TOTAL
CONF.shared 'NUM/TOTAL' #Split tests into multiple machines in CI
--testSequencer RPATH #Customize tests run order.
CONF.testSequencer RPATH #By default: failed tests, then previously long tests, then tests in big files.
#Should be a CLASS extending from '@jest/test-sequencer' and redefining:
# - constructor(OPTS)
# - must call super(OPTS)
# - OPTS: globalConfig CONF, contexts ARR
# - sort(TEST_ARR)->[PROMISE_]TEST_ARR
CONF.transform.REGEXP #MODULE for preprocessing files (e.g. Babel)
#Can also be [MODULE, MODULE_OPTS]
#Available ones:
# - babel-jest (package babel-jest): Babel
## - ts-jest: TypeScript
CONF.transformIgnorePatterns #'REGEXP'_ARR (def: ['node_modules', '.pnp.js'])
┌──────────────────┐
│ PROGRAMMATIC │
└──────────────────┘
JEST.runCLI
(CONF[, 'PROJECT_DIR'_ARR])->>OBJ#
buildArgv #CONF
┌─────────┐
│ GUI │
└─────────┘
MAJESTIC ==> ##Electron app wrapper around jest CLI:
## - like CLI: reporting, watch mode, snapshots update
## - files tree
## - coverage status
┌─────────────────┐
│ ENVIRONMENT │
└─────────────────┘
CONF.globals.VAR #Set a global variable
#Must be JSON serializable
ENV #Sandboxed global environment. Can be:
# - node (package jest-environment-node) (def)
# - uses VM core module
# - ENV_OPTS are additional global variables
# - jsdom (package jest-environment-jsdom)
# - uses JSDOM (see its doc)
# - can use CONF.testEnvironmentOptions.url for OPTS.url
# - ENV_OPTS:
# - any JSDOM option
# - console (def: global.console)
# - jsdom-abstract (package @jest/environment-jsdom-abstract)
# - same but can choose JSDom version
CONF.customExportConditions #PACKAGE.imports|exports CONDITIONS.
#Def: ['node', 'node-addons'] for 'node', 'browser' for 'jsdom'
new Env(CONFIG) #
ENV.setup|teardown()->PROMISE #
ENV.runScript(SCRIPT)->VAL #
--env
CONF.testEnvironment #ENV
/**
* @jest-environment ENV
*/ #Another way to set ENV, on top of test file
CONF.testEnvironmentOptions #ENV_OPTS
/**
* @jest-environment-options OBJ
*/ #Another way to set ENV_OPTS, on top of test()
TEST ISOLATED ENVIRONMENT ==> #Each top-level test file (and the files required by it) runs in a separate ENV.runScript(),
#i.e. an isolated environment:
# - global variables
# - before|afterAll|Each(), CONF.setup*
# - mocking (generic, modules, timers)
CONF.sandboxInjectedGlobals #'VAR'_ARR. Make using those global variables faster in test files, by bypassing global lookup.
JEST.getSeed()->NUM #
--seed=NUM #Value of JEST.getSeed(). Def: random
--showSeed #
--waitNextEventLoopTurnFor
UnhandledRejectionEvents #Wait one more tick to report rejectionHandled, uncaughtException and unhandledRejection
┌───────────────┐
│ REPORTING │
└───────────────┘
--silent #
--verbose
CONF.verbose #BOOL (def: false)
--useStderr #Use stderr instead of stdout
--colors #Force colors
--noStackTrace #On failure, do not show both stack trace and sample of source code that failed.
-e
--expand #Show multiline equality failures in full instead of as diff
┌───────────┐
│ SPEED │
└───────────┘
CONF.testTimeout
--testTimeout NUM #Test timeout (def: 5000)
JEST.setTimeout(NUM) #JEST.setTimeout() must be put in CONF.setupFilesAfterEnv
#Can also use last argument NUM to it|before|after*()
--slow-test-threshold NUM #Print that test is slow if longer than NUMs (def: 5)
--openHandlesTimeout NUM #Timeout to warn when a file handle is left open (def: 1000, in ms)
--[no-]cache #Cache several information, including filesystem information
#Def: enabled
--clearCache #
CONF.cacheDirectory #DIR (def: '/tmp/<path>')
--logHeapUsage #Show amount of memory used by each test file
--detectLeaks #BOOL (def: false)
CONF.detectLeaks #Reports memory leaks
--workerIdleMemoryLimit NUM|STR #If worker consumes more memory, restart it. Meant as a fix for leaks.
#STR is 'NUM%' or 'NUM[K[i]B|M[i]B|G[i]B]'
JEST.isEnvironmentTornDown()->BOOL#True when process exited due to timeout or similar
┌─────────────────┐
│ PARALLELISM │
└─────────────────┘
[x|f]it.concurrent #Run concurrently with other it.concurrent() tests inside same test file (I/O parallelism)
[.only|skip|each](...) #FUNC must return a PROMISE
#Current limitation: beforeAll|Each() will be run afterwards not before
CONF.maxConcurrency NUM #Number of tests per file to run concurrently at once
--maxConcurrency NUM #Def: 5
CONF.maxWorkers NUM|NUM% #Number of top-level test files to run concurrently
-w NUM|NUM% #Each top-level test file will be started with CHILD_PROCESS.fork(), i.e. in different CPU cores (CPU parallelism)
--maxWorkers NUM|NUM% #Def NUM: OS.availableParallelism()
#The describe|it() inside each top-level test file will be run serially (unless it.concurrent())
-i
--runInBand #Same as --maxWorkers 1
--workerThreads #Use worker threads instead of child processes
--randomize #Randomize tests order in each test file
┌─────────────┐
│ LINTING │
└─────────────┘
VERSION ==> ##Module 'eslint-plugin-jest' (28.11.0)
##There is a recommended set with half of rules being error or warn, and another with all
##SETTINGS:
## - globalAliases.VAR 'VAR2'_ARR: e.g. 'describe' aliased to something else
## - globalPackage 'MODULE': MODULE with same globals as Jest (e.g. 'node:test', 'vitest' or 'bun:test')
jest/no-jasmine-globals ##Avoid Jasmine-specific code, e.g. jasmine.*, spyOn*() or fail|pending()
jest/prefer-import-jest-globals ##Import Jest instead of using global variables
[OPTS] ##OPTS:
## - types STR_ARR: which type of variables among 'jest', 'test', 'describe', 'hook', 'expect', 'unknown'
jest/valid-describe-callback ##No async describe()
jest/max-describe [OPTS] ##OPTS.max NUM (def: 5) describe() nested
jest/no-export ##No ESM export in test files
jest/require-top-level-describe ##No test|before*|after*() outside describe()
[OPTS] ##OPTS:
## - maxNumberOfTopLevelDescribes NUM (def: Inf): maximum number of top-level describe()
jest/no-hooks [OPTS] ##No before|afterEach|All()
##OPTS: ignore 'before|afterEach|All'_ARR
jest/no-duplicate-hooks [OPTS] ##No before|afterEach|All() twice in same block
jest/prefer-hooks-on-top ##No before|afterEach|All() must be before any it()
jest/prefer-hooks-in-order ##Order: beforeAll(), beforeEach(), afterEach(), afterAll()
jest/require-hook [OPTS] ##Use before|afterEach|All() instead of code that is inside describe()
##OPTS:
## - allowedFunctionCalls 'FUNC'_ARR
jest/prefer-each ##Prefer it.each() over for loop + it()
jest/no-identical-title ##No identical test titles within same describe()
jest/no-empty-title ##No describe|it('')
jest/lowercase-name-title [OPTS] ##Title should start with lowercase
##OPTS:
## - ignore 'it|test|describe'_ARR
## - allow STR_ARR
## - ignoreTopLevelDescribe BOOL (def: false): ignore top-level describe()
jest/valid-title [OPTS] ##Title should not:
## - start|end with whitespaces
## - start with "test"|"describe"
##OPTS:
## - ignoreTypeOfDescribeName BOOL (def: false): for describe(STR) not only it(STR)
## - ignoreTypeOfTestName BOOL (def: false): not for it(STR)
## - ignoreSpaces BOOL (def: false): trim spaces
## - disallowedWords STR_ARR (def: []): case-insensitive
## - must[Not]Match[.describe|test|it] REGEXP or [REGEXP, 'MESSAGE']
jest/consistent-test-it [OPTS] ##Whether to name it() or test()
##OPTS:
## - withinDescribe (def: 'it')
## - fn (def: 'test'): outside describe()
jest/no-disabled-tests ##No skipped tests
jest/no-focused-tests ##No "only" tests
jest/no-commented-out-tests ##No commented tests
jest/no-test-prefixes ##Prefer *.only|skip() over x|f*()
jest/prefer-todo ##Prefer *.todo() over empty test function
jest/no-done-callback ##Prefer PROMISE over using FUNC2 inside it|before*|after*()
jest/no-test-return-statement ##Should not return values in it()
jest/valid-expect-in-promise ##Should return PROMISE in it() if there is one
jest/no-conditional-in-test ##Try to move if|switch outside tests
jest/no-conditional-expect ##No expect() inside if
##Also, no try|catch inside tests (prefer toThrow())
jest/no-standalone-expect [OPTS] ##No expect() outside test
##OPTS:
## - additionalTestBlockFunctions 'FUNC'_ARR: alternative names for `test`
jest/expect-expect [OPTS] ##At least one expect() per test
##OPTS:
## - assertFunctionNames 'FUNC_GLOB'_ARR (def: ['assert'])
## - additionalTestBlockFunctions 'FUNC'_ARR: alternative names for `test`
jest/valid-expect [OPTS] ##No expect() with no argument or no following assertion
##OPTS:
## - alwaysAwait BOOL (def: false): expect(...).resolves should be awaited
## - minArgs|maxArgs NUM (def: 1):
## - number of arguments for expect()
## - Useful with third-party libraries that change how expect() is called
## - asyncMatchers 'FUNC'_ARR (def: ['toResolve', 'toReject']): which matchers are async
jest/max-expects [OPTS] ##OPTS.max NUM (def: 5) EXPECT per test
jest/prefer-strict-equal ##Prefer EXPECT.toStrictEqual() over EXPECT.toEqual()
jest/prefer-to-be ##Prefer EXPECT.toBe*() over EXPECT.toEqual() for simple types
jest/prefer-equality-matcher ##Prefer EXPECT.toBe|[Strict]Equal() when possible
jest/prefer-to-have-length ##Prefer EXPECT_ARR.toHaveLength() over EXPECT(ARR.length).toBe|to[Strict]Equal()
jest/prefer-to-contain ##Prefer EXPECT_ARR.toContain(VAL) over EXPECT(ARR.includes(VAL)).toBe|to[Strict]Equal(BOOL)
jest/prefer-called-with ##Prefer EXPECT.toHaveBeenCalledWith() over EXPECT.toHaveBeenCalled()
jest/prefer-comparison-matcher ##Prefer EXPECT.toBeGreater|Less*() when possible
jest/require-to-throw-message ##Must do EXPECT.toThrow(STR|REGEXP) not EXPECT.toThrow()
jest/prefer-expect-resolves ##Prefer EXPECT(PROMISE).resolves|rejects over EXPECT(await PROMISE)
jest/prefer-expect-assertions ##Should use either EXPECT.assertions() or EXPECT.hasAssertions() in every test
[OPTS] ##OPTS
## - onlyFunctionsWithAsyncKeyword BOOL (def: false): only if test() is async
## - onlyFunctionsWithExpectInLoop BOOL (def: false): only if assertions is within a loop
## - onlyFunctionsWithExpectInCallback BOOL (def: false): only if assertions are within a callback
jest/no-alias-methods ##Should not use EXPECT.* aliases, i.e.:
## - toThrow() instead of toThrowError()
## - toHaveBeen*Called() instead of toBeCalled*() or last|nthCalled*()
## - toHave*Returned() instead of toReturn*() or last|nthReturned*()
jest/no-restricted-matchers
[OPTS] ##Avoid EXPECT.VARR where VARR is from OPTS.VARR null|'ERROR_MESSAGE'
jest/no-restricted-jest-methods
[OPTS] ##Avoid JEST.VARR where VARR is from OPTS.VARR null|'ERROR_MESSAGE'
jest/prefer-spy-on ##Prefer JEST.spyOn() over JEST.fn()
jest/prefer-jest-mocked ##Prefer JEST.mocked() over new jest.Mock[Function|Class|Object]()
jest/
prefer-mock-promise-shorthand ##Prefer JEST.mock* over JEST.mockImplementation()
jest/no-mocks-import ##Avoid direct require('__mocks__/MODULE.js')
jest/no-untyped-mock-factory ##Use JEST.mock<TYPE>(..., FUNC) instead of JEST.mock(..., FUNC), when using TypeScript
jest/no-deprecated-functions ##No deprecated methods like
[OPTS] ##JEST.resetModuleRegistry|addMatchers|requireActual|requireMock|runTimersToTime|genMockFromModule
##OPTS:
## - version NUM
jest/no-large-snapshots [OPTS] ##Snapshot files should be small
##OPTS:
## - maxSize (def: 12, in lines): for external and (unless inlineMaxSize defined) inline snapshots
## - inlineMaxSize (def: 6, in lines): for inline snapshots
## - allowedSnapshots.PATH ['NAME', CONTENT_REGEXP]
jest/
no-interpolation-in-snapshots ##Avoid `${...}` with inline snapshots
jest/prefer-snapshot-hints [STR] ##Must use 'NAME|ERROR' with toMatchSnapshot|toThrowErrorMatchingSnapshot()
jest/unbound-method ##Adapt @typescript-eslint/unbound-method for Jest
jest/no-confusing-set-timeout ##JEST.setTimeout() must be in global scope, called once, before describe|test|it()
jest/padding-around-TYPE ##Enforce empty lines in-between TYPEs:
## - before|after-all|each, describe, test, expect
## - all: all of the above
ESLINT-IMPORT-RESOLVER-JEST ==> ##See eslint-plugin-import doc