前端自動(dòng)化測(cè)試框架 Jest 極簡(jiǎn)教程

前端自動(dòng)化測(cè)試框架 Jest 極簡(jiǎn)教程

Delightful JavaScript Testing. https://jestjs.io

Jest是由Facebook發(fā)布的開源的、基于Jasmine的JavaScript單元測(cè)試框架丧鸯。集成了 Mocha踊挠,chai挤庇,jsdom哲身,sinon等功能。

具有零配置、內(nèi)置代碼覆蓋率、強(qiáng)大的Mocks等特點(diǎn)边酒。

Jest源于測(cè)試Web聊天應(yīng)用。Facebook的一名軟件工程師Jeff Morrison半年前又重拾這個(gè)項(xiàng)目狸窘,改善它的性能甚纲,并將其開源。

Jest的目標(biāo)是減少開始測(cè)試一個(gè)項(xiàng)目所要花費(fèi)的時(shí)間和認(rèn)知負(fù)荷朦前,因此它提供了大部分你需要的現(xiàn)成工具:快速的命令行接口、Mock工具集以及它的自動(dòng)模塊Mock系統(tǒng)鹃操。此外韭寸,如果你在尋找隔離工具例如Mock庫(kù),大部分其它工具將讓你在測(cè)試中(甚至經(jīng)常在你的主代碼中)寫一些不盡如人意的樣板代碼荆隘,以使其生效恩伺。

Jest與Jasmine框架的區(qū)別是在后者之上增加了一些層。最值得注意的是椰拒,運(yùn)行測(cè)試時(shí)晶渠,Jest會(huì)自動(dòng)模擬依賴。Jest自動(dòng)為每個(gè)依賴的模塊生成Mock燃观,并默認(rèn)提供這些Mock褒脯,這樣就可以很容易地隔離模塊的依賴。

Jest 測(cè)試的生命周期

jest 測(cè)試提供了一些測(cè)試的生命周期 API缆毁,可以輔助我們?cè)诿總€(gè) case 的開始和結(jié)束做一些處理番川。 這樣,在進(jìn)行一些和數(shù)據(jù)相關(guān)的測(cè)試時(shí)脊框,可以在測(cè)試前準(zhǔn)備一些數(shù)據(jù)颁督,在測(cè)試后,清理測(cè)試數(shù)據(jù)浇雹。

4 個(gè)主要的生命周期函數(shù):

  • beforeAll(fn, timeout): 同 afterAll沉御,不同之處在于在所有測(cè)試開始前執(zhí)行
  • beforeEach(fn, timeout): 同 afterEach,不同之處在于在每個(gè)測(cè)試開始前執(zhí)行
  • afterEach(fn, timeout): 每個(gè) test 執(zhí)行完后執(zhí)行 fn昭灵,timeout 含義同上
  • afterAll(fn, timeout): 當(dāng)前文件中的所有測(cè)試執(zhí)行完成后執(zhí)行 fn, 如果 fn 是 promise吠裆,jest 會(huì)等待 timeout 毫秒伐谈,默認(rèn) 5000.

配置項(xiàng)

  1. testMatch
    設(shè)置識(shí)別哪些文件是測(cè)試文件(glob形式),與testRegex互斥硫痰,不能同時(shí)寫
testMatch: ['\*\*/\_\_tests\_\_/\*\*/\*.js?(x)','\*\*/?(*.)(spec|test).js?(x)']
  1. testRegex
    設(shè)置識(shí)別哪些文件是測(cè)試文件(正則形式)衩婚,與testMatch互斥,不能同時(shí)寫
testRegex: '(/\_\_tests\_\_).*|(\\\\.|/)(test|spec))\\\\.jsx?$'
  1. testRnviroment
    測(cè)試環(huán)境效斑,默認(rèn)值是:jsdom非春,可修改為node
testEnvironment: 'jsdom'
  1. rootDir
    默認(rèn)值:當(dāng)前目錄,一般是package.json所在的目錄缓屠。
rootDir: ' '
  1. moduleFileExtensions
    測(cè)試文件的類型
moduleFileExtensions: ['js','json','jsx','node']

一般配置:

module.exports = {
    testMatch: ['<rootDir>/test/\*\*/\*.js'],
    testEnvironment: 'jsdom',
    rootDir: '',
    moduleFileExtensions: ['js','json','jsx','node']
}

Jest CLI Options


id: cli
title: Jest CLI Options


The jest command line runner has a number of useful options. You can run jest --help to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's Configuration options can also be specified through the CLI.

Here is a brief overview:

Running from the command line

Run all tests (default):

jest

Run only the tests that were specified with a pattern or filename:

jest my-test #or
jest path/to/my-test.js

Run tests related to changed files based on hg/git (uncommitted files):

jest -o

Run tests related to path/to/fileA.js and path/to/fileB.js:

jest --findRelatedTests path/to/fileA.js path/to/fileB.js

Run tests that match this spec name (match against the name in describe or test, basically).

jest -t name-of-spec

Run watch mode:

jest --watch #runs jest -o by default
jest --watchAll #runs all tests

Watch mode also enables to specify the name or path to a file to focus on a specific set of tests.

Using with yarn

If you run Jest via yarn test, you can pass the command line arguments directly as Jest arguments.

Instead of:

jest -u -t="ColorPicker"

you can use:

yarn test -u -t="ColorPicker"

Using with npm scripts

If you run Jest via npm test, you can still use the command line arguments by inserting a -- between npm test and the Jest arguments.

Instead of:

jest -u -t="ColorPicker"

you can use:

npm test -- -u -t="ColorPicker"

Camelcase & dashed args support

Jest supports both camelcase and dashed arg formats. The following examples will have equal result:

jest --collect-coverage
jest --collectCoverage

Arguments can also be mixed:

jest --update-snapshot --detectOpenHandles

Options

Note: CLI options take precedence over values from the Configuration.


Reference

jest <regexForTestFiles>

When you run jest with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. Depending on your terminal, you may need to quote this argument: jest "my.*(complex)?pattern". On Windows, you will need to use / as a path separator or escape \ as \\.

--bail

Alias: -b. Exit the test suite immediately upon n number of failing test suite. Defaults to 1.

--cache

Whether to use the cache. Defaults to true. Disable the cache using --no-cache. Note: the cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower.

If you want to inspect the cache, use --showConfig and look at the cacheDirectory value. If you need to clear the cache, use --clearCache.

--changedFilesWithAncestor

Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to --onlyChanged.

--changedSince

Runs tests related the changes since the provided branch. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to --onlyChanged.

--ci

When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with --updateSnapshot.

--clearCache

Deletes the Jest cache directory and then exits without running tests. Will delete cacheDirectory if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling jest --showConfig. Note: clearing the cache will reduce performance.

--collectCoverageFrom=<glob>

A glob pattern relative to <rootDir> matching the files that coverage info needs to be collected from.

--colors

Forces test results output highlighting even if stdout is not a TTY.

--config=<path>

Alias: -c. The path to a Jest config file specifying how to find and execute tests. If no rootDir is set in the config, the directory containing the config file is assumed to be the rootDir for the project. This can also be a JSON-encoded value which Jest will use as configuration.

--coverage

Indicates that test coverage information should be collected and reported in the output. This option is also aliased by --collectCoverage.

--debug

Print debugging info about your Jest config.

--detectOpenHandles

Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use --forceExit in order for Jest to exit to potentially track down the reason. Implemented using async_hooks, so it only works in Node 8 and newer.

--env=<environment>

The test environment used for all tests. This can point to any file or node module. Examples: jsdom, node or path/to/my-environment.js.

--errorOnDeprecated

Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.

--expand

Alias: -e. Use this flag to show full diffs and errors instead of a patch.

--findRelatedTests <spaceSeparatedListOfSourceFiles>

Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.

--forceExit

Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. Note: This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use --detectOpenHandles to help track it down.

--help

Show the help information, similar to this page.

--init

Generate a basic configuration file. Based on your project, Jest will ask you a few questions that will help to generate a jest.config.js file with a short description for each option.

--json

Prints the test results in JSON. This mode will send all other test output and user messages to stderr.

--outputFile=<filename>

Write test results to a file when the --json option is also specified.

--lastCommit

Run all tests affected by file changes in the last commit made. Behaves similarly to --onlyChanged.

--listTests

Lists all tests as JSON that Jest will run given the arguments, and exits. This can be used together with --findRelatedTests to know which tests Jest will run.

--logHeapUsage

Logs the heap usage after every test. Useful to debug memory leaks. Use together with --runInBand and --expose-gc in node.

--maxWorkers=<num>|<string>

Alias: -w. Specifies the maximum number of workers the worker-pool will spawn for running tests. This defaults to the number of the cores available on your machine. It may be useful to adjust this in resource limited environments like CIs but the default should be adequate for most use-cases.

For environments with variable CPUs available, you can use percentage based configuration: --maxWorkers=50%

--noStackTrace

Disables stack trace in test results output.

--notify

Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing.

--onlyChanged

Alias: -o. Attempts to identify which tests to run based on which files have changed in the current repository. Only works if you're running tests in a git/hg repository at the moment and requires a static dependency graph (ie. no dynamic requires).

--passWithNoTests

Allows the test suite to pass when no files are found.

--projects <path1> ... <pathN>

Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the projects configuration option. Note that if configuration files are found in the specified paths, all projects specified within those configuration files will be run.

--reporters

Run tests with specified reporters. Reporter options are not available via CLI. Example with multiple reporters:

jest --reporters="default" --reporters="jest-junit"

--runInBand

Alias: -i. Run all tests serially in the current process, rather than creating a worker pool of child processes that run tests. This can be useful for debugging.

--runTestsByPath

Run only the tests that were specified with their exact paths.

Note: The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files

--setupTestFrameworkScriptFile=<file>

The path to a module that runs some code to configure or set up the testing framework before each test. Beware that files imported by the setup script will not be mocked during testing.

--showConfig

Print your Jest config and then exits.

--silent

Prevent tests from printing messages through the console.

--testNamePattern=<regex>

Alias: -t. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like "GET /api/posts with auth", then you can use jest -t=auth.

Note: The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks.

--testLocationInResults

Adds a location field to test results. Useful if you want to report the location of a test in a reporter.

Note that column is 0-indexed while line is not.

{
  "column": 4,
  "line": 5
}

--testPathPattern=<regex>

A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use / as a path separator or escape \ as \\.

--testPathIgnorePatterns=[array]

An array of regexp pattern strings that is tested against all tests paths before executing the test. Contrary to --testPathPattern, it will only run those test with a path that does not match with the provided regexp expressions.

--testRunner=<path>

Lets you specify a custom test runner.

--updateSnapshot

Alias: -u. Use this flag to re-record every snapshot that fails during this test run. Can be used together with a test suite pattern or with --testNamePattern to re-record snapshots.

--useStderr

Divert all output to stderr.

--verbose

Display individual test results with the test suite hierarchy.

--version

Alias: -v. Print the version and exit.

--watch

Watch files for changes and rerun tests related to changed files. If you want to re-run all tests when a file has changed, use the --watchAll option instead.

--watchAll

Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the --watch option.

--watchman

Whether to use watchman for file crawling. Defaults to true. Disable using --no-watchman.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末奇昙,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子敌完,更是在濱河造成了極大的恐慌储耐,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,602評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件滨溉,死亡現(xiàn)場(chǎng)離奇詭異什湘,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)晦攒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門闽撤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人脯颜,你說(shuō)我怎么就攤上這事哟旗。” “怎么了栋操?”我有些...
    開封第一講書人閱讀 152,878評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵闸餐,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我矾芙,道長(zhǎng)舍沙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,306評(píng)論 1 279
  • 正文 為了忘掉前任剔宪,我火速辦了婚禮场勤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘歼跟。我一直安慰自己和媳,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,330評(píng)論 5 373
  • 文/花漫 我一把揭開白布哈街。 她就那樣靜靜地躺著留瞳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪骚秦。 梳的紋絲不亂的頭發(fā)上她倘,一...
    開封第一講書人閱讀 49,071評(píng)論 1 285
  • 那天璧微,我揣著相機(jī)與錄音,去河邊找鬼硬梁。 笑死前硫,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的荧止。 我是一名探鬼主播屹电,決...
    沈念sama閱讀 38,382評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼跃巡!你這毒婦竟也來(lái)了危号?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,006評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤素邪,失蹤者是張志新(化名)和其女友劉穎外莲,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體兔朦,經(jīng)...
    沈念sama閱讀 43,512評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡偷线,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,965評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了沽甥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片淋昭。...
    茶點(diǎn)故事閱讀 38,094評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖安接,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情英融,我是刑警寧澤盏檐,帶...
    沈念sama閱讀 33,732評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站驶悟,受9級(jí)特大地震影響胡野,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜痕鳍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,283評(píng)論 3 307
  • 文/蒙蒙 一硫豆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧笼呆,春花似錦熊响、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,286評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至铭若,卻和暖如春洪碳,著一層夾襖步出監(jiān)牢的瞬間递览,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,512評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工瞳腌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留绞铃,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,536評(píng)論 2 354
  • 正文 我出身青樓嫂侍,卻偏偏與公主長(zhǎng)得像儿捧,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子吵冒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,828評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 前言 隨著Web業(yè)務(wù)的日益復(fù)雜化和多元化纯命,前端開發(fā)也有了前端工程化的概念,前端工程化成為目前前端架構(gòu)中重要的一環(huán)痹栖,...
    CharmSun閱讀 1,212評(píng)論 0 1
  • 大多數(shù)開發(fā)者都知道需要寫單元測(cè)試亿汞,但是不知道每個(gè)單元測(cè)試應(yīng)用的主要內(nèi)容以及如何做單元測(cè)試,在介紹jest測(cè)試框架前...
    糖小工閱讀 6,044評(píng)論 0 11
  • 春節(jié)假期雖然只有短短的七天揪阿,可是回到家這七天仿佛進(jìn)入了另一個(gè)世界疗我。拋開工作,面對(duì)著父母兄弟南捂,同學(xué)好友吴裤,鄰里親朋,談...
    小清讀書閱讀 456評(píng)論 0 0
  • 墨溢硯溺健,花滿樓麦牺,長(zhǎng)卷在手,手倦午夢(mèng)幽鞭缭。 餐后逍遙自捫腹剖膳,香茗一口,銷魂似飲酒岭辣。 竹絲繩吱晒,玉壺冰,焚膏繼晷沦童,半生夢(mèng)回...
    張鋒_bdce閱讀 175評(píng)論 0 0
  • 登壺梯山 山路不遠(yuǎn)仑濒,馬蹄印在鐘表盤上 湖中有明月,山頂?shù)牡朗空驹诓铇湎?或許我錯(cuò)了 梯是向上的能到達(dá)彼岸 又或許我...
    阿貍貓貓閱讀 303評(píng)論 0 0