1. 安装
yarn global add jest-cli
or
npm install -g jest-cli
备注:可以安装为依赖不用全局安装
2. 项目代码
a. 项目初始化yarn init -y
├── package.json
├── sum.js
├── sun.test.js
└── yarn.lockb. package.json{"name": "jestdemo","version": "1.0.0","main": "index.js","license": "MIT","dependencies": {"jest-cli": "^22.0.4"},"scripts": {"test": "jest "}
}c. sum.js(就是一个简单的sum 模块)module.exports=sum;
function sum(a,b){return a+b;
}d. sum.test.js (按照约定 {name}.test.js 格式的是测试文件)const sum = require("./sum.js");
describe("sum test suit", () => {test("test sum result", () => {expect(sum(1, 3)).toBe(4);})test("appdemo", () => {expect(sum(1, 4)).toBeGreaterThan(2);})
});
e. 运行测试
yarn run test
结果
PASS .\sum.test.jssum test suit√ test sum result (7ms)√ appdemo (2ms)Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.443s
Ran all test suites.
Done in 3.46s.
f. 添加代码测试覆盖率
修改package.json
"scripts": {"test": "jest --watchAll --coverage"}
界面:运行,如下图:
代码覆盖率如下图:
3. jest 命令行参数
Usage: jest.js [--config=] [TestPathPattern]Options:--help, -h Show help [boolean]--all The opposite of `onlyChanged`. If`onlyChanged` is set by default, running jestwith `--all` will force Jest to run all testsinstead of running only tests related tochanged files.--automock Automock all files by default. [boolean]--bail, -b Exit the test suite immediately upon the firstfailing test. [boolean]--browser Respect the "browser" field in package.jsonwhen resolving modules. Some packages exportdifferent versions based on whether they areoperating in node.js or a browser. [boolean]--cache Whether to use the transform cache. Disablethe cache using --no-cache. [boolean]--cacheDirectory The directory where Jest should store itscached dependency information. [string]--changedFilesWithAncestor When used together with `--onlyChanged`, itruns tests related to the current changes andthe changes made in the last commit. (NOTE:this only works for hg repos) [boolean]--ci Whether to run Jest in continuous integration(CI) mode. This option is on by default inmost popular CI environments. It will preventsnapshots from being written unless explicitlyrequested. [boolean] [default: false]--clearCache Clears the configured Jest cache directory andthen exits. Default directory can be found bycalling jest --showConfig [boolean]--clearMocks Automatically clear mock calls and instancesbetween every test. Equivalent to callingjest.clearAllMocks() between each test.[boolean]--collectCoverage Alias for --coverage. [boolean]--collectCoverageFrom relative to glob pattern matchingthe files that coverage info needs to becollected from. [string]--collectCoverageOnlyFrom Explicit list of paths coverage will berestricted to. [array]--color Forces test results output color highlighting(even if stdout is not a TTY). Set to false ifyou would like to have no colors. [boolean]--colors Alias for `--color`. [boolean]--config, -c The path to a jest config file specifying howto find and execute tests. If no rootDir isset in the config, the current directory isassumed to be the rootDir for the project.This can also be a JSON encoded value whichJest will use as configuration. [string]--coverage Indicates that test coverage informationshould be collected and reported in theoutput. [boolean]--coverageDirectory The directory where Jest should output itscoverage files. [string]--coveragePathIgnorePatterns An array of regexp pattern strings that arematched against all file paths beforeexecuting the test. If the file pathmatchesany of the patterns, coverage information willbe skipped. [array]--coverageReporters A list of reporter names that Jest uses whenwriting coverage reports. Any istanbulreporter can be used. [array]--coverageThreshold A JSON string with which will be used toconfigure minimum threshold enforcement forcoverage results [string]--debug Print debugging info about your jest config.[boolean]--detectLeaks **EXPERIMENTAL**: Detect memory leaks intests. After executing a test, it will try togarbage collect the global object used, andfail if it was leaked[boolean] [default: false]--env The test environment used for all tests. Thiscan point to any file or node module.Examples: `jsdom`, `node` or`path/to/my-environment.js` [string]--expand, -e Use this flag to show full diffs instead of apatch. [boolean]--findRelatedTests Find related tests for a list of source filesthat were passed in as arguments. Useful forpre-commit hook integration to run the minimalamount of tests necessary. [boolean]--forceExit Force Jest to exit after all tests havecompleted running. This is useful whenresources set up by test code cannot beadequately cleaned up. [boolean]--globalSetup The path to a module that runs before AllTests. [string]--globalTeardown The path to a module that runs after AllTests. [string]--globals A JSON string with map of global variablesthat need to be available in all testenvironments. [string]--haste A JSON string with map of variables for thehaste module system [string]--json Prints the test results in JSON. This modewill send all other test output and usermessages to stderr. [boolean]--lastCommit Will run all tests affected by file changes inthe last commit made. [boolean]--listTests Lists all tests Jest will run given thearguments and exits. Most useful in a CIsystem together with `--findRelatedTests` todetermine the tests Jest will run based onspecific files [boolean] [default: false]--logHeapUsage Logs the heap usage after every test. Usefulto debug memory leaks. Use together with`--runInBand` and `--expose-gc` in node.[boolean]--mapCoverage Maps code coverage reports against originalsource code when transformers supply sourcemaps. [boolean]--maxWorkers, -w Specifies the maximum number of workers theworker-pool will spawn for running tests. Thisdefaults to the number of the cores availableon your machine. (its usually best not tooverride this default) [number]--moduleDirectories An array of directory names to be searchedrecursively up from the requiring module'slocation. [array]--moduleFileExtensions An array of file extensions your modules use.If you require modules without specifying afile extension, these are the extensions Jestwill look for. [array]--moduleNameMapper A JSON string with a map from regularexpressions to module names that allow to stubout resources, like images or styles with asingle module [string]--modulePathIgnorePatterns An array of regexp pattern strings that arematched against all module paths before thosepaths are to be considered "visible" to themodule loader. [array]--modulePaths An alternative API to setting the NODE_PATHenv variable, modulePaths is an array ofabsolute paths to additional locations tosearch when resolving modules. [array]--noStackTrace Disables stack trace in test results output[boolean]--notify Activates notifications for test results.[boolean]--onlyChanged, -o Attempts to identify which tests to run basedon which files have changed in the currentrepository. Only works if you're running testsin a git repository at the moment. [boolean]--onlyFailures, -f Run tests that failed in the previousexecution. [boolean]--outputFile Write test results to a file when the --jsonoption is also specified. [string]--passWithNoTests Will not fail if no tests are found (forexample while using `--testPathPattern`.)[boolean] [default: false]--preset A preset that is used as a base for Jest'sconfiguration. [string]--projects A list of projects that use Jest to run alltests of all projects in a single instance ofJest. [array]--reporters A list of custom reporters for the test suite.[array]--resetMocks Automatically reset mock state between everytest. Equivalent to callingjest.resetAllMocks() between each test.[boolean]--resetModules If enabled, the module registry for every testfile will be reset before running eachindividual test. [boolean]--resolver A JSON string which allows the use of a customresolver. [string]--rootDir The root directory that Jest should scan fortests and modules within. [string]--roots A list of paths to directories that Jestshould use to search for files in. [array]--runInBand, -i Run all tests serially in the current process(rather than creating a worker pool of childprocesses that run tests). This is sometimesuseful for debugging, but such use cases arepretty rare. [boolean]--runTestsByPath Used when provided patterns are exact filepaths. This avoids converting them into aregular expression and matching it againstevery single file. [boolean] [default: false]--setupFiles The paths to modules that run some code toconfigure or set up the testing environmentbefore each test. [array]--setupTestFrameworkScriptFile The path to a module that runs some code toconfigure or set up the testing frameworkbefore each test. [string]--showConfig Print your jest config and then exits.[boolean]--silent Prevent tests from printing messages throughthe console. [boolean]--snapshotSerializers A list of paths to snapshot serializer modulesJest should use for snapshot testing. [array]--testEnvironment Alias for --env [string]--testFailureExitCode Exit code of `jest` command if the test runfailed [string]--testLocationInResults Add `location` information to the test results[boolean] [default: false]--testMatch The glob patterns Jest uses to detect testfiles. [array]--testNamePattern, -t Run only tests with a name that matches theregex pattern. [string]--testPathIgnorePatterns An array of regexp pattern strings that arematched against all test paths beforeexecuting the test. If the test path matchesany of the patterns, it will be skipped.[array]--testPathPattern A regexp pattern string that is matchedagainst all tests paths before executing thetest. [array]--testRegex The regexp pattern Jest uses to detect testfiles. [string]--testResultsProcessor Allows the use of a custom results processor.This processor must be a node module thatexports a function expecting as the firstargument the result object [string]--testRunner Allows to specify a custom test runner. Thedefault is `jasmine2`. A path to a customtest runner can be provided:`/path/to/testRunner.js`. [string]--testURL This option sets the URL for the jsdomenvironment. [string]--timers Setting this value to fake allows the use offake timers for functions such as setTimeout.[string]--transform A JSON string which maps from regularexpressions to paths to transformers. [string]--transformIgnorePatterns An array of regexp pattern strings that arematched against all source file paths beforetransformation. [array]--unmockedModulePathPatterns An array of regexp pattern strings that arematched against all modules before the moduleloader will automatically return a mock forthem. [array]--updateSnapshot, -u Use this flag to re-record snapshots. Can beused together with a test suite pattern orwith `--testNamePattern` to re-record snapshotfor test matching the pattern [boolean]--useStderr Divert all output to stderr. [boolean]--verbose Display individual test results with the testsuite hierarchy. [boolean]--watch Watch files for changes and rerun testsrelated to changed files. If you want tore-run all tests when a file has changed, usethe `--watchAll` option. [boolean]--watchAll Watch files for changes and rerun all tests.If you want to re-run only the tests relatedto the changed files, use the `--watch`option. [boolean]--watchPathIgnorePatterns An array of regexp pattern strings that arematched against all paths before trigger testre-run in watch mode. If the test path matchesany of the patterns, it will be skipped.[array]--watchman Whether to use watchman for file crawling.Disable using --no-watchman. [boolean]Documentation: https://facebook.github.io/jest/Done in 0.69s.
4. 参考资料
https://facebook.github.io/jest/
https://github.com/rongfengliang/jestdemo