热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

jestjs测试框架简单方便人性化

1.安装yarnglobaladdjest-cliornpminstall-gjest-cli备注:可以安装为依赖不用全局安装2.项目代码a.项目初始化yarn
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




推荐阅读
  • 在对WordPress Duplicator插件0.4.4版本的安全评估中,发现其存在跨站脚本(XSS)攻击漏洞。此漏洞可能被利用进行恶意操作,建议用户及时更新至最新版本以确保系统安全。测试方法仅限于安全研究和教学目的,使用时需自行承担风险。漏洞编号:HTB23162。 ... [详细]
  • 本文介绍了如何利用Shell脚本高效地部署MHA(MySQL High Availability)高可用集群。通过详细的脚本编写和配置示例,展示了自动化部署过程中的关键步骤和注意事项。该方法不仅简化了集群的部署流程,还提高了系统的稳定性和可用性。 ... [详细]
  • 为了在Hadoop 2.7.2中实现对Snappy压缩和解压功能的原生支持,本文详细介绍了如何重新编译Hadoop源代码,并优化其Native编译过程。通过这一优化,可以显著提升数据处理的效率和性能。此外,还探讨了编译过程中可能遇到的问题及其解决方案,为用户提供了一套完整的操作指南。 ... [详细]
  • 在Cisco IOS XR系统中,存在提供服务的服务器和使用这些服务的客户端。本文深入探讨了进程与线程状态转换机制,分析了其在系统性能优化中的关键作用,并提出了改进措施,以提高系统的响应速度和资源利用率。通过详细研究状态转换的各个环节,本文为开发人员和系统管理员提供了实用的指导,旨在提升整体系统效率和稳定性。 ... [详细]
  • 在使用 Qt 进行 YUV420 图像渲染时,由于 Qt 本身不支持直接绘制 YUV 数据,因此需要借助 QOpenGLWidget 和 OpenGL 技术来实现。通过继承 QOpenGLWidget 类并重写其绘图方法,可以利用 GPU 的高效渲染能力,实现高质量的 YUV420 图像显示。此外,这种方法还能显著提高图像处理的性能和流畅性。 ... [详细]
  • Python 程序转换为 EXE 文件:详细解析 .py 脚本打包成独立可执行文件的方法与技巧
    在开发了几个简单的爬虫 Python 程序后,我决定将其封装成独立的可执行文件以便于分发和使用。为了实现这一目标,首先需要解决的是如何将 Python 脚本转换为 EXE 文件。在这个过程中,我选择了 Qt 作为 GUI 框架,因为之前对此并不熟悉,希望通过这个项目进一步学习和掌握 Qt 的基本用法。本文将详细介绍从 .py 脚本到 EXE 文件的整个过程,包括所需工具、具体步骤以及常见问题的解决方案。 ... [详细]
  • PHP预处理常量详解:如何定义与使用常量 ... [详细]
  • PTArchiver工作原理详解与应用分析
    PTArchiver工作原理及其应用分析本文详细解析了PTArchiver的工作机制,探讨了其在数据归档和管理中的应用。PTArchiver通过高效的压缩算法和灵活的存储策略,实现了对大规模数据的高效管理和长期保存。文章还介绍了其在企业级数据备份、历史数据迁移等场景中的实际应用案例,为用户提供了实用的操作建议和技术支持。 ... [详细]
  • Android 构建基础流程详解
    Android 构建基础流程详解 ... [详细]
  • 全面解析JavaScript代码注释技巧与标准规范
    在Web前端开发中,JavaScript代码的可读性和维护性至关重要。本文将详细介绍如何有效地使用注释来提高代码的可读性,并探讨JavaScript代码注释的最佳实践和标准规范。通过合理的注释,开发者可以更好地理解和维护复杂的代码逻辑,提升团队协作效率。 ... [详细]
  • 本文介绍了一种自定义的Android圆形进度条视图,支持在进度条上显示数字,并在圆心位置展示文字内容。通过自定义绘图和组件组合的方式实现,详细展示了自定义View的开发流程和关键技术点。示例代码和效果展示将在文章末尾提供。 ... [详细]
  • 为了确保iOS应用能够安全地访问网站数据,本文介绍了如何在Nginx服务器上轻松配置CertBot以实现SSL证书的自动化管理。通过这一过程,可以确保应用始终使用HTTPS协议,从而提升数据传输的安全性和可靠性。文章详细阐述了配置步骤和常见问题的解决方法,帮助读者快速上手并成功部署SSL证书。 ... [详细]
  • 使用 ListView 浏览安卓系统中的回收站文件 ... [详细]
  • MATLAB字典学习工具箱SPAMS:稀疏与字典学习的详细介绍、配置及应用实例
    SPAMS(Sparse Modeling Software)是一个强大的开源优化工具箱,专为解决多种稀疏估计问题而设计。该工具箱基于MATLAB,提供了丰富的算法和函数,适用于字典学习、信号处理和机器学习等领域。本文将详细介绍SPAMS的配置方法、核心功能及其在实际应用中的典型案例,帮助用户更好地理解和使用这一工具箱。 ... [详细]
  • 在Linux系统中,网络配置是至关重要的任务之一。本文详细解析了Firewalld和Netfilter机制,并探讨了iptables的应用。通过使用`ip addr show`命令来查看网卡IP地址(需要安装`iproute`包),当网卡未分配IP地址或处于关闭状态时,可以通过`ip link set`命令进行配置和激活。此外,文章还介绍了如何利用Firewalld和iptables实现网络流量控制和安全策略管理,为系统管理员提供了实用的操作指南。 ... [详细]
author-avatar
潮爆啊--_317
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有