前端自动化测试框架 Jest 极简教程

前端自动化测试框架 Jest 极简教程

Delightful JavaScript Testing. https://jestjs.io

Jest是由Facebook发布的开源的、基于Jasmine的JavaScript单元测试框架。集成了 Mocha,chai,jsdom,sinon等功能。

具有零配置、内置代码覆盖率、强大的Mocks等特点。

Jest源于测试Web聊天应用。Facebook的一名软件工程师Jeff Morrison半年前又重拾这个项目,改善它的性能,并将其开源。

Jest的目标是减少开始测试一个项目所要花费的时间和认知负荷,因此它提供了大部分你需要的现成工具:快速的命令行接口、Mock工具集以及它的自动模块Mock系统。此外,如果你在寻找隔离工具例如Mock库,大部分其它工具将让你在测试中(甚至经常在你的主代码中)写一些不尽如人意的样板代码,以使其生效。

Jest与Jasmine框架的区别是在后者之上增加了一些层。最值得注意的是,运行测试时,Jest会自动模拟依赖。Jest自动为每个依赖的模块生成Mock,并默认提供这些Mock,这样就可以很容易地隔离模块的依赖。

Jest 测试的生命周期

jest 测试提供了一些测试的生命周期 API,可以辅助我们在每个 case 的开始和结束做一些处理。 这样,在进行一些和数据相关的测试时,可以在测试前准备一些数据,在测试后,清理测试数据。

4 个主要的生命周期函数:

  • beforeAll(fn, timeout): 同 afterAll,不同之处在于在所有测试开始前执行
  • beforeEach(fn, timeout): 同 afterEach,不同之处在于在每个测试开始前执行
  • afterEach(fn, timeout): 每个 test 执行完后执行 fn,timeout 含义同上
  • afterAll(fn, timeout): 当前文件中的所有测试执行完成后执行 fn, 如果 fn 是 promise,jest 会等待 timeout 毫秒,默认 5000.

配置项

  1. testMatch
    设置识别哪些文件是测试文件(glob形式),与testRegex互斥,不能同时写
testMatch: ['\*\*/\_\_tests\_\_/\*\*/\*.js?(x)','\*\*/?(*.)(spec|test).js?(x)']
  1. testRegex
    设置识别哪些文件是测试文件(正则形式),与testMatch互斥,不能同时写
testRegex: '(/\_\_tests\_\_).*|(\\\\.|/)(test|spec))\\\\.jsx?$'
  1. testRnviroment
    测试环境,默认值是:jsdom,可修改为node
testEnvironment: 'jsdom'
  1. rootDir
    默认值:当前目录,一般是package.json所在的目录。
rootDir: ' '
  1. moduleFileExtensions
    测试文件的类型
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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,864评论 6 494
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,175评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,401评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,170评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,276评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,364评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,401评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,179评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,604评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,902评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,070评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,751评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,380评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,077评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,312评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,924评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,957评论 2 351

推荐阅读更多精彩内容

  • 前言 随着Web业务的日益复杂化和多元化,前端开发也有了前端工程化的概念,前端工程化成为目前前端架构中重要的一环,...
    CharmSun阅读 1,215评论 0 1
  • 大多数开发者都知道需要写单元测试,但是不知道每个单元测试应用的主要内容以及如何做单元测试,在介绍jest测试框架前...
    糖小工阅读 6,049评论 0 11
  • 春节假期虽然只有短短的七天,可是回到家这七天仿佛进入了另一个世界。抛开工作,面对着父母兄弟,同学好友,邻里亲朋,谈...
    小清读书阅读 463评论 0 0
  • 墨溢砚,花满楼,长卷在手,手倦午梦幽。 餐后逍遥自扪腹,香茗一口,销魂似饮酒。 竹丝绳,玉壶冰,焚膏继晷,半生梦回...
    张锋_bdce阅读 175评论 0 0
  • 登壶梯山 山路不远,马蹄印在钟表盘上 湖中有明月,山顶的道士站在茶树下 或许我错了 梯是向上的能到达彼岸 又或许我...
    一粟小阅读 308评论 0 0