{"id":20669122,"url":"https://github.com/jackchoumine/jest-practice","last_synced_at":"2025-09-03T17:47:09.749Z","repository":{"id":124185371,"uuid":"288200691","full_name":"jackchoumine/jest-practice","owner":"jackchoumine","description":"jest 测试框架学习","archived":false,"fork":false,"pushed_at":"2020-08-17T14:24:44.000Z","size":45,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-17T13:30:36.324Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jackchoumine.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-17T14:22:51.000Z","updated_at":"2020-08-17T14:24:47.000Z","dependencies_parsed_at":null,"dependency_job_id":"05d416a9-a3b6-4d0f-b92d-cf3e115592cf","html_url":"https://github.com/jackchoumine/jest-practice","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jackchoumine%2Fjest-practice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jackchoumine%2Fjest-practice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jackchoumine%2Fjest-practice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jackchoumine%2Fjest-practice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jackchoumine","download_url":"https://codeload.github.com/jackchoumine/jest-practice/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242883695,"owners_count":20200979,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-16T20:13:04.397Z","updated_at":"2025-03-10T16:03:32.430Z","avatar_url":"https://github.com/jackchoumine.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!--\n * @Description: \n * @Date: 2020-08-16 12:54:57 +0800\n * @Author: JackChouMine\n * @LastEditTime: 2020-08-17 22:19:06 +0800\n * @LastEditors: JackChouMine\n--\u003e\n# Jest 前端测试学习\n\n## 环境搭建\n安装 `jest`\n```bash\nnpm i -D jest\n```\n安装了`26.4.0`版本的jest：\n```json\n{\n  \"name\": \"jest-practice\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Jest 前端测试框架学习\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"jest\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"jest\": \"^26.4.0\"\n  }\n}\n```\n\n编写测试用例 `test/index.spec.js`\n```js\ntest('1 + 3 = 4', () =\u003e {\n  expect(1 + 3).toBe(4)\n})\n```\n运行`npm run test`,没有报错，显示通过的用例，就搭建好了测试环境。\n`test` 函数的第一个参数是字符串，对用例的说明，expect 返回一个期望对象，`toBe`是一个匹配器。\n当 Jest 运行时，它会跟踪所有失败的匹配器，以便它可以为你打印出很好的错误消息。\n`toBe`使用`Object.is` 来测试精确相等，如果想检测对象的值相等，使用`toEqual`,递归检测对象或者数组的每个字段是否相等。`not.toBe` 和 `toBe`匹配器。\n\n## 使用匹配器\n\n匹配器是一种断言，可使用匹配器来测试你的函数期望返回的结果，和期望一致，则测试通过，否不通过。\n\n### 真值匹配器\n\n在测试中， `undefined`、`null`、`false`都是假值，我们往往需要精确知道一个假值是什么，有以下匹配器：\n- toBeNull 只匹配 null\n- toBeUndefined 只匹配 undefined\n- toBeDefined 与 toBeUndefined 相反\n- toBeTruthy 匹配任何 if 语句为真\n- toBeFalsy 匹配任何 if 语句为假\n\n### 数字\n\n数学比较里有`\u003e`、`\u003e=`、`\u003c`、`\u003c=`，也有对应的比较器：\n- toBeGreaterThan\n- toBeGreaterThanOrEqual\n- toBeLessThan\n- toBeLessThanOrEqual\n- toBe 精确相等\n- toBeCloseTo 浮点数近似相等，计算机精度有限，无法判断浮点数精确相等\n\n`NaN`、`Infinity` 等特殊数字，有匹配器吗？\n\n\n### 字符串\n\n`toMatch` 匹配器可用正则来检测字符串包含的字符。\n```js\ntest('there is no I in team', () =\u003e {\n  expect('team').not.toMatch(/I/)\n})\n\ntest('but there is a \"stop\" in Christoph', () =\u003e {\n  expect('Christoph').toMatch(/stop/)\n})\n```\n\n`toContain` 用来检测数组、字符串和可迭代对象是否包含某一项。\n\n```js\ntest('the shopping list has beer on it', () =\u003e {\n  expect([1, 2, 3]).toContain(1)\n  expect([1, 2, 3]).not.toContain(4)\n  expect(new Set(['beer'])).toContain('beer')\n  expect('JackChou').toContain('Jack')\n})\n```\n\n### 错误匹配器\n\n测试函数是否抛出错误。\n`toThrow`，可传递一个错误信息和错误。\n\n```js\nfunction compileAndroidCode () {\n  throw new Error('you are using the wrong JDK')\n}\n\ntest('compiling android goes as expected', () =\u003e {\n  expect(compileAndroidCode).toThrow()\n  expect(compileAndroidCode).toThrow(Error)\n\n  // You can also use the exact error message or a regexp\n  expect(compileAndroidCode).toThrow('you are using the wrong JDK')\n  expect(compileAndroidCode).toThrow(/JDK/)\n})\n```\n[完整的匹配器](https://jestjs.io/docs/zh-Hans/expect#tobenan)，社区也提供了更多的匹配器。\n\n## 代码覆盖率\n\n单元测试：对系统中一个模块进行检查。可能是一个函数、一个组件等。\n集成测试：在单元测试基础上，把所有模块集成成系统，再进行检查，又叫联合测试和组装测试。\n\n编写 Jest 配置文件：\n```bash\njest --init\n```\n配置覆盖率执行脚本：\n```bash\n\"coverage\":\"jest --coverage\"\n```\n\n引入测试代码：\n```js\nconst { sum } = require('../src/index')\ntest('sum', () =\u003e {\n  expect(sum(10, 20)).toBe(30)\n})\n```\n执行覆盖率脚本，得到一个覆盖率报告：\n```bash\n----------|---------|----------|---------|---------|-------------------\nFile      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s\n----------|---------|----------|---------|---------|-------------------\nAll files |     100 |      100 |     100 |     100 |                  \n index.js |     100 |      100 |     100 |     100 |                  \n----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       10 passed, 10 total\nSnapshots:   0 total\nTime:        2.323 s, estimated 3 s\nRan all test suites.\n```\n同时生成`coverage`目录，里面有一个覆盖率报告，打开`index.html`即可查看。\n可在`jest.config.js` 配置文件里修改覆盖率报告的目录：\n\n```bash\ncoverageDirectory: 'coverage',\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjackchoumine%2Fjest-practice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjackchoumine%2Fjest-practice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjackchoumine%2Fjest-practice/lists"}