"use strict";(self.webpackChunkfes_js=self.webpackChunkfes_js||[]).push([[977],{5393:(n,s,e)=>{e.r(s),e.d(s,{data:()=>a});const a={key:"v-3cd5a4ef",path:"/reference/plugin/plugins/jest.html",title:"@fesjs/plugin-jest",lang:"zh-CN",frontmatter:{},excerpt:"",headers:[{level:2,title:"启用方式",slug:"启用方式",children:[]},{level:2,title:"约定",slug:"约定",children:[]},{level:2,title:"命令",slug:"命令",children:[]},{level:2,title:"配置",slug:"配置",children:[{level:3,title:"args 变量",slug:"args-变量",children:[]},{level:3,title:"配置文件",slug:"配置文件",children:[]},{level:3,title:"优先级",slug:"优先级",children:[]}]}],filePathRelative:"reference/plugin/plugins/jest.md",git:{updatedTime:1664436338e3,contributors:[{name:"winixt",email:"haizekuo@gmail.com",commits:1}]}}},914:(n,s,e)=>{e.r(s),e.d(s,{default:()=>v});var a=e(6252);const r=(0,a._)("h1",{id:"fesjs-plugin-jest",tabindex:"-1"},[(0,a._)("a",{class:"header-anchor",href:"#fesjs-plugin-jest","aria-hidden":"true"},"#"),(0,a.Uk)(" @fesjs/plugin-jest")],-1),t=(0,a.Uk)("集成 "),l={href:"https://www.jestjs.cn/",target:"_blank",rel:"noopener noreferrer"},i=(0,a.Uk)("Jest"),p=(0,a.Uk)(" 测试框架,目前只支持单元测试和覆盖测试。"),o=(0,a.uE)('

启用方式

package.json 中引入依赖:

{\n    "dependencies": {\n        "@fesjs/fes": "^2.0.0",\n        "@fesjs/plugin-jest": "^2.0.0"\n    },\n}\n
1
2
3
4
5
6

约定

例如测试文件 add.js

fes-template\n├── __tests__\n│   └── add.js\n└── src\n    ├── .fes\n    └── utils\n        └── sum.js\n
1
2
3
4
5
6
7

内容如下:

import sum from '@/utils/sum';\ntest('adds 1 + 2 to equal 3', () => {\n    expect(sum(1, 2)).toBe(3);\n});\n\n
1
2
3
4
5

命令

fes 上注册 test 命令:

$ fes test\n
1

配置

',13),c=(0,a.Uk)("插件实现 Jest 的全部配置,具体请查看 "),u={href:"https://www.jestjs.cn/docs/configuration#reference",target:"_blank",rel:"noopener noreferrer"},b=(0,a.Uk)("文档-configuration"),m=(0,a.Uk)("。 也可以使用 "),h=(0,a._)("code",null,"-h",-1),d=(0,a.Uk)(" 打印配置帮助信息:"),f=(0,a.uE)('

args 变量

$ fes test -h\n
1

打印配置帮助信息:

$ fes test -h\nUsage: fes test [options]\n\nrun unit tests with jest\n\nOptions:\n  --all                         The opposite of `onlyChanged`. If `onlyChanged`\n                                is set by default, running jest with `--all`\n                                will force Jest to run all tests instead of\n                                running only tests related to changed files.\n  --automock                    Automock all files by default.\n  -b --bail                     Exit the test suite immediately after `n`\n                                number of failing tests.\n  --browser                     Respect the "browser" field in package.json\n                                when resolving modules. Some packages export\n                                different versions based on whether they are\n                                operating in node.js or a browser.\n  --cache                       Whether to use the transform cache. Disable the\n                                cache using --no-cache.\n  --cacheDirectory              The directory where Jest should store its\n                                cached  dependency information.\n  --changedFilesWithAncestor    Runs tests related to the current changes and\n                                the changes made in the last commit. Behaves\n                                similarly to `--onlyChanged`.\n  --changedSince                Runs tests related to the changes since the\n                                provided branch. If the current branch has\n                                diverged from the given branch, then only\n                                changes made locally will be tested. Behaves\n                                similarly to `--onlyChanged`.\n  --ci                          Whether to run Jest in continuous integration\n                                (CI) mode. This option is on by default in most\n                                popular CI environments. It will prevent\n                                snapshots from being written unless explicitly\n                                requested.\n  --clearCache                  Clears the configured Jest cache directory and\n                                then exits. Default directory can be found by\n                                calling jest --showConfig\n  --clearMocks                  Automatically clear mock calls and instances\n                                between every test. Equivalent to calling\n                                jest.clearAllMocks() between each test.\n  --collectCoverage             Alias for --coverage.\n  --collectCoverageFrom         A glob pattern relative to <rootDir> matching\n                                the files that coverage info needs to be\n                                collected from.\n  --collectCoverageOnlyFrom     Explicit list of paths coverage will be\n                                restricted to.\n  --color                       Forces test results output color highlighting\n                                (even if stdout is not a TTY). Set to false if\n                                you would like to have no colors.\n  --colors                      Alias for `--color`.\n  -c --config                   The path to a jest config file specifying how\n                                to find and execute tests. If no rootDir is set\n                                in the config, the directory containing the\n                                config file is assumed to be the rootDir for\n                                the project.This can also be a JSON encoded\n                                value which Jest will use as configuration.\n  --coverage                    Indicates that test coverage information should\n                                be collected and reported in the output.\n  --coverageDirectory           The directory where Jest should output its\n                                coverage files.\n  --coveragePathIgnorePatterns  An array of regexp pattern strings that are\n                                matched against all file paths before executing\n                                the test. If the file pathmatches any of the\n                                patterns, coverage information will be skipped.\n  --coverageProvider            Select between Babel and V8 to collect coverage\n  --coverageReporters           A list of reporter names that Jest uses when\n                                writing coverage reports. Any istanbul reporter\n                                can be used.\n  --coverageThreshold           A JSON string with which will be used to\n                                configure minimum threshold enforcement for\n                                coverage results\n  --debug                       Print debugging info about your jest config.\n  --detectLeaks                 **EXPERIMENTAL**: Detect memory leaks in tests.\n                                After executing a test, it will try to garbage\n                                collect the global object used, and fail if it\n                                was leaked\n  --detectOpenHandles           Print out remaining open handles preventing\n                                Jest from exiting at the end of a test run.\n                                Implies `runInBand`.\n  --env                         The test environment used for all tests. This\n                                can point to any file or node module. Examples:\n                                `jsdom`, `node` or `path/to/my-environment.js`\n  --errorOnDeprecated           Make calling deprecated APIs throw helpful\n                                error messages.\n  -e --expand                   Use this flag to show full diffs instead of a\n                                patch.\n  --filter                      Path to a module exporting a filtering\n                                function. This method receives a list of tests\n                                which can be manipulated to exclude tests from\n                                running. Especially useful when used in\n                                conjunction with a testing infrastructure to\n                                filter known broken tests.\n  --findRelatedTests            Find related tests for a list of source files\n                                that were passed in as arguments. Useful for\n                                pre-commit hook integration to run the minimal\n                                amount of tests necessary.\n  --forceExit                   Force Jest to exit after all tests have\n                                completed running. This is useful when\n                                resources set up by test code cannot be\n                                adequately cleaned up.\n  --globalSetup                 The path to a module that runs before All\n                                Tests.\n  --globalTeardown              The path to a module that runs after All Tests.\n  --globals                     A JSON string with map of global variables that\n                                need to be available in all test environments.\n  --haste                       A JSON string with map of variables for the\n                                haste module system\n  --init                        Generate a basic configuration file\n  --injectGlobals               Should Jest inject global variables or not\n  --json                        Prints the test results in JSON. This mode will\n                                send all other test output and user messages to\n                                stderr.\n  --lastCommit                  Run all tests affected by file changes in the\n                                last commit made. Behaves similarly to\n                                `--onlyChanged`.\n  --listTests                   Lists all tests Jest will run given the\n                                arguments and exits. Most useful in a CI system\n                                together with `--findRelatedTests` to determine\n                                the tests Jest will run based on specific files\n  --logHeapUsage                Logs the heap usage after every test. Useful to\n                                debug memory leaks. Use together with\n                                `--runInBand` and `--expose-gc` in node.\n  --mapCoverage                 Maps code coverage reports against original source code when transformers supply source maps.\n\n  DEPRECATED\n  --maxConcurrency              Specifies the maximum number of tests that are\n                                allowed to runconcurrently. This only affects\n                                tests using `test.concurrent`.\n  -w --maxWorkers               Specifies the maximum number of workers the\n                                worker-pool will spawn for running tests. This\n                                defaults to the number of the cores available\n                                on your machine. (its usually best not to\n                                override this default)\n  --moduleDirectories           An array of directory names to be searched\n                                recursively up from the requiring module's\n                                location.\n  --moduleFileExtensions        An array of file extensions your modules use.\n                                If you require modules without specifying a\n                                file extension, these are the extensions Jest\n                                will look for.\n  --moduleNameMapper            A JSON string with a map from regular\n                                expressions to module names or to arrays of\n                                module names that allow to stub out resources,\n                                like images or styles with a single module\n  --modulePathIgnorePatterns    An array of regexp pattern strings that are\n                                matched against all module paths before those\n                                paths are to be considered "visible" to the\n                                module loader.\n  --modulePaths                 An alternative API to setting the NODE_PATH env\n                                variable, modulePaths is an array of absolute\n                                paths to additional locations to search when\n                                resolving modules.\n  --noStackTrace                Disables stack trace in test results output\n  --notify                      Activates notifications for test results.\n  --notifyMode                  Specifies when notifications will appear for\n                                test results.\n  -o --onlyChanged              Attempts to identify which tests to run based\n                                on which files have changed in the current\n                                repository. Only works if you're running tests\n                                in a git or hg repository at the moment.\n  -f --onlyFailures             Run tests that failed in the previous\n                                execution.\n  --outputFile                  Write test results to a file when the --json\n                                option is also specified.\n  --passWithNoTests             Will not fail if no tests are found (for\n                                example while using `--testPathPattern`.)\n  --preset                      A preset that is used as a base for Jest's\n                                configuration.\n  --prettierPath                The path to the "prettier" module used for\n                                inline snapshots.\n  --projects                    A list of projects that use Jest to run all\n                                tests of all projects in a single instance of\n                                Jest.\n  --reporters                   A list of custom reporters for the test suite.\n  --resetMocks                  Automatically reset mock state between every\n                                test. Equivalent to calling\n                                jest.resetAllMocks() between each test.\n  --resetModules                If enabled, the module registry for every test\n                                file will be reset before running each\n                                individual test.\n  --resolver                    A JSON string which allows the use of a custom\n                                resolver.\n  --restoreMocks                Automatically restore mock state and\n                                implementation between every test. Equivalent\n                                to calling jest.restoreAllMocks() between each\n                                test.\n  --rootDir                     The root directory that Jest should scan for\n                                tests and modules within.\n  --roots                       A list of paths to directories that Jest should\n                                use to search for files in.\n  -i --runInBand                Run all tests serially in the current process\n                                (rather than creating a worker pool of child\n                                processes that run tests). This is sometimes\n                                useful for debugging, but such use cases are\n                                pretty rare.\n  --runTestsByPath              Used when provided patterns are exact file\n                                paths. This avoids converting them into a\n                                regular expression and matching it against\n                                every single file.\n  --runner                      Allows to use a custom runner instead of Jest's\n                                default test runner.\n  --selectProjects              Run only the tests of the specified\n                                projects.Jest uses the attribute `displayName`\n                                in the configuration to identify each project.\n  --setupFiles                  A list of paths to modules that run some code\n                                to configure or set up the testing environment\n                                before each test.\n  --setupFilesAfterEnv          A list of paths to modules that run some code\n                                to configure or set up the testing framework\n                                before each test\n  --showConfig                  Print your jest config and then exits.\n  --silent                      Prevent tests from printing messages through\n                                the console.\n  --skipFilter                  Disables the filter provided by --filter.\n                                Useful for CI jobs, or local enforcement when\n                                fixing tests.\n  --snapshotSerializers         A list of paths to snapshot serializer modules\n                                Jest should use for snapshot testing.\n  --testEnvironment             Alias for --env\n  --testEnvironmentOptions      Test environment options that will be passed to\n                                the testEnvironment. The relevant options\n                                depend on the environment.\n  --testFailureExitCode         Exit code of `jest` command if the test run\n                                failed\n  --testLocationInResults       Add `location` information to the test results\n  --testMatch                   The glob patterns Jest uses to detect test\n                                files.\n  -t --testNamePattern          Run only tests with a name that matches the\n                                regex pattern.\n  --testPathIgnorePatterns      An array of regexp pattern strings that are\n                                matched against all test paths before executing\n                                the test. If the test path matches any of the\n                                patterns, it will be skipped.\n  --testPathPattern             A regexp pattern string that is matched against\n                                all tests paths before executing the test.\n  --testRegex                   A string or array of string regexp patterns\n                                that Jest uses to detect test files.\n  --testResultsProcessor        Allows the use of a custom results processor.\n                                This processor must be a node module that\n                                exports a function expecting as the first\n                                argument the result object.\n  --testRunner                  Allows to specify a custom test runner. The\n                                default is  `jasmine2`. A path to a custom test\n                                runner can be provided:\n                                `<rootDir>/path/to/testRunner.js`.\n  --testSequencer               Allows to specify a custom test sequencer. The\n                                default is `@jest/test-sequencer`. A path to a\n                                custom test sequencer can be provided:\n                                `<rootDir>/path/to/testSequencer.js`\n  --testTimeout                 This option sets the default timeouts of test\n                                cases.\n  --testURL                     This option sets the URL for the jsdom\n                                environment.\n  --timers                      Setting this value to fake allows the use of\n                                fake timers for functions such as setTimeout.\n  --transform                   A JSON string which maps from regular\n                                expressions to paths to transformers.\n  --transformIgnorePatterns     An array of regexp pattern strings that are\n                                matched against all source file paths before\n                                transformation.\n  --unmockedModulePathPatterns  An array of regexp pattern strings that are\n                                matched against all modules before the module\n                                loader will automatically return a mock for\n                                them.\n  -u --updateSnapshot           Use this flag to re-record snapshots. Can be\n                                used together with a test suite pattern or with\n                                `--testNamePattern` to re-record snapshot for\n                                test matching the pattern\n  --useStderr                   Divert all output to stderr.\n  --verbose                     Display individual test results with the test\n                                suite hierarchy.\n  --watch                       Watch files for changes and rerun tests related\n                                to changed files. If you want to re-run all\n                                tests when a file has changed, use the\n                                `--watchAll` option.\n  --watchAll                    Watch files for changes and rerun all tests. If\n                                you want to re-run only the tests related to\n                                the changed files, use the `--watch` option.\n  --watchPathIgnorePatterns     An array of regexp pattern strings that are\n                                matched against all paths before trigger test\n                                re-run in watch mode. If the test path matches\n                                any of the patterns, it will be skipped.\n  --watchman                    Whether to use watchman for file crawling.\n                                Disable using --no-watchman.\n  -h, --help                    display help for command\n\n
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

比如覆盖测试:

fes test --coverage\n
1

配置文件

除了插件内置的默认配置之外,插件遵循 Jest的配置文件规范,约定项目根目录下的 jest.config.js 为用户配置文件,约定 packages.jsonjest 属性内容也是配置。

优先级

args 配置 > package.json中的 jest > jest.config.js > 默认配置

',10),g={},v=(0,e(3744).Z)(g,[["render",function(n,s){const e=(0,a.up)("OutboundLink");return(0,a.wg)(),(0,a.iD)(a.HY,null,[r,(0,a._)("p",null,[t,(0,a._)("a",l,[i,(0,a.Wm)(e)]),p]),o,(0,a._)("p",null,[c,(0,a._)("a",u,[b,(0,a.Wm)(e)]),m,h,d]),f],64)}]])},3744:(n,s)=>{s.Z=(n,s)=>{const e=n.__vccOpts||n;for(const[n,a]of s)e[n]=a;return e}}}]);