前端自动化测试:Jest 测试框架应用

开发 前端 自动化
作为一个面向前端的测试框架, Jest 可以利用其特有的快照测试功能,通过比对UI 代码生成的快照文件,实现对 React 等常见前端框架的自动测试。

[[407449]]

Jest : https://jestjs.io/zh-Hans/是 Facebook 出品的一个 JavaScript 开源测试框架。

相对其他测试框架,其一大特点就是就是内置了常用的测试工具,比如零配置、自带断言、测试覆盖率工具等功能,实现了开箱即用。

Jest 适用但不局限于使用以下技术的项目:Babel、TypeScript、 Node、 React、Angular、Vue 等。

Jest 主要特点:

  • 零配置
  • 自带断言
  • 作为一个面向前端的测试框架, Jest 可以利用其特有的快照测试功能,通过比对UI 代码生成的快照文件,实现对 React 等常见前端框架的自动测试。
  • Jest 的测试用例是并行执行的,而且只执行发生改变的文件所对应的测试,提升了测试速度。
  • 测试覆盖率
  • Mock 模拟

快速体验 Jest

安装 Jest 到项目中:

  1. npm install --save-dev jest 
  1. //math.js 
  2. functionadd (a, b) { 
  3.   return a * b 
  4.  
  5. functionsubtract (x, y) { 
  6.   return x - y 
  7.  
  8. module.exports= { 
  9.   add
  10.   subtract 
  1. //test.js ==> math.test.js 
  2. const { add, subtract } =require('./math'
  3.  
  4. test('测试加法', () => { 
  5.   expect(add(1,2)).toBe(3) 
  6. }) 
  7.  
  8. test('测试减法', () => { 
  9.   expect(subtract(2,1)).toBe(1) 
  10. }) 
  1. //package.json 
  2.   "scripts":{ 
  3.     "test":"jest" 
  4.   } 

jest 命令会运行项目中所有以 .test.js 结尾的文件

最后运行测试命令:

  1. npm run test 

解析:

  • jest 找到项目中所有以 .test.js 结尾的文件并运行
  • jest 会给测试文件提供 test、expect 等全局函数,所以在测试文件中可以直接使用
  • jest 为测试结果提供了良好的日志输出

解决 vscode 中 jest 代码提示问题

  1. npm i -D @types/jest 

注意:@types/jest 必须安装到项目的根目录,并且以根目录的方式在 vscode 中打开,否则不生效。或者说只要是 vscode 打开的项目根目录有 @types/jest 这个包就可以了。

配置文件

  1. npx jest--init 

配置文件生成选项:

  • 是否使用 ts ;
  • 使用哪种测试环境;
  • 使用 jest 收集测试覆盖率报告;
  • 使用那种引擎检测覆盖率:v8 处于实验性阶段,建议 Node v14 后使用,babel 较为成熟
  • 每次测试时,是否自动清除 mock 实例;

详细配置信息参考:https://jestjs.io/docs/zh-Hans/configuration。

  1. //jest.config.js 
  2. /* 
  3.  * For a detailedexplanation regarding each configuration property, visit: 
  4.  *https://jestjs.io/docs/en/configuration.html 
  5.  */ 
  6.  
  7. module.exports= { 
  8.   // 自动 mock 所有导入的外部模块 
  9.   // automock: false
  10.  
  11.   // 在指定次数失败后停止运行测试 
  12.   // bail: 0, 
  13.  
  14.   // The directory where Jest should store its cached dependencyinformation 
  15.   // cacheDirectory:"/private/var/folders/5h/_98rffpj1z95b_0dm76lvzm40000gn/T/jest_dx"
  16.  
  17.   // 在每个测试之间自动清除 mock 调用和实例 
  18.   clearMocks:true
  19.  
  20.   // 是否收集测试覆盖率信息 
  21.   // collectCoverage: false
  22.  
  23.   // 一个 glob 模式数组,指示应该为其收集覆盖率信息的一组文件 
  24.   // collectCoverageFrom: undefined, 
  25.  
  26.   // 测试覆盖率报错文件输出的目录 
  27.   coverageDirectory:"coverage"
  28.  
  29.   // 忽略测试覆盖率统计 
  30.   // coveragePathIgnorePatterns: [ 
  31.   //  "/node_modules/" 
  32.   // ], 
  33.  
  34.   // 指示应该使用哪个提供程序检测代码的覆盖率,默认是 babel,可选 v8,但是 v8 不太稳定,建议Node 14 以上版本使用 
  35.   // coverageProvider: "babel"
  36.  
  37.   // A list of reporter names that Jest uses when writingcoverage reports 
  38.   // coverageReporters: [ 
  39.   //   "json"
  40.   //   "text"
  41.   //   "lcov"
  42.   //   "clover" 
  43.   // ], 
  44.  
  45.   // An object that configures minimum threshold enforcement forcoverage results 
  46.   // coverageThreshold: undefined, 
  47.  
  48.   // A path to a custom dependency extractor 
  49.   // dependencyExtractor: undefined, 
  50.  
  51.   // Make calling deprecated APIs throw helpful error messages 
  52.   // errorOnDeprecated: false
  53.  
  54.   // Force coverage collection from ignored files using an arrayof glob patterns 
  55.   // forceCoverageMatch: [], 
  56.  
  57.   // A path to a module which exports an async function that istriggered once before all test suites 
  58.   // globalSetup: undefined, 
  59.  
  60.   // A path to a module which exports an async function that istriggered once after all test suites 
  61.   // globalTeardown: undefined, 
  62.  
  63.   // A set of global variables that need to be available in alltest environments 
  64.   // globals: {}, 
  65.  
  66.   // The maximum amount of workers used to run your tests. Canbe specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPUamount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2workers. 
  67.   // maxWorkers: "50%"
  68.  
  69.   // An array of directory names to be searched recursively upfrom the requiring module's location 
  70.   // moduleDirectories: [ 
  71.   //  "node_modules" 
  72.   // ], 
  73.  
  74.   // An array of file extensions your modules use 
  75.   // moduleFileExtensions: [ 
  76.   //   "js"
  77.   //   "json"
  78.   //   "jsx"
  79.   //   "ts"
  80.   //   "tsx"
  81.   //   "node" 
  82.   // ], 
  83.  
  84.   // A map from regular expressions to module names or to arraysof module names that allow to stub out resources with a single module 
  85.   // moduleNameMapper: {}, 
  86.  
  87.   // An array of regexp pattern strings, matched against allmodule paths before considered 'visible' to the module loader 
  88.   // modulePathIgnorePatterns: [], 
  89.  
  90.   // Activates notifications for test results 
  91.   // notify: false
  92.  
  93.   // An enum that specifies notification mode. Requires {notify: true } 
  94.   // notifyMode: "failure-change"
  95.  
  96.   // A preset that is used as a base for Jest's configuration 
  97.   // preset: undefined, 
  98.  
  99.   // Run tests from one or more projects 
  100.   // projects: undefined, 
  101.  
  102.   // Use this configuration option to add custom reporters toJest 
  103.   // reporters: undefined, 
  104.  
  105.   // Automatically reset mock state between every test 
  106.   // resetMocks: false
  107.  
  108.   // Reset the module registry before running each individualtest 
  109.   // resetModules: false
  110.  
  111.   // A path to a custom resolver 
  112.   // resolver: undefined, 
  113.  
  114.   // Automatically restore mock state between every test 
  115.   // restoreMocks: false
  116.  
  117.   // The root directory that Jest should scan for tests andmodules within 
  118.   // rootDir: undefined, 
  119.  
  120.   // A list of paths to directories that Jest should use tosearch for files in 
  121.   // roots: [ 
  122.   //  "<rootDir>" 
  123.   // ], 
  124.  
  125.   // Allows you to use a custom runner instead of Jest's defaulttest runner 
  126.   // runner: "jest-runner"
  127.  
  128.   // The paths to modules that run some code to configure or setup the testing environment before each test 
  129.   // setupFiles: [], 
  130.  
  131.   // A list of paths to modules that run some code to configureor set up the testing framework before each test 
  132.   // setupFilesAfterEnv: [], 
  133.  
  134.   // The number of seconds after which a test is considered asslow and reported as such in the results. 
  135.   // slowTestThreshold: 5, 
  136.  
  137.   // A list of paths to snapshot serializer modules Jest shoulduse for snapshot testing 
  138.   // snapshotSerializers: [], 
  139.  
  140.   // The test environment that will be used for testing 
  141.   // testEnvironment: "jest-environment-jsdom"
  142.  
  143.   // Options that will be passed to the testEnvironment 
  144.   // testEnvironmentOptions: {}, 
  145.  
  146.   // Adds a location field to test results 
  147.   // testLocationInResults: false
  148.  
  149.   // The glob patterns Jest uses to detect test files 
  150.   // testMatch: [ 
  151.   //  "**/__tests__/**/*.[jt]s?(x)"
  152.   //  "**/?(*.)+(spec|test).[tj]s?(x)" 
  153.   // ], 
  154.  
  155.   // An array of regexp pattern strings that are matched againstall test paths, matched tests are skipped 
  156.   // testPathIgnorePatterns: [ 
  157.   //  "/node_modules/" 
  158.   // ], 
  159.  
  160.   // The regexp pattern or array of patterns that Jest uses todetect test files 
  161.   // testRegex: [], 
  162.  
  163.   // This option allows the use of a custom results processor 
  164.   // testResultsProcessor: undefined, 
  165.  
  166.   // This option allows use of a custom test runner 
  167.   // testRunner: "jasmine2"
  168.  
  169.   // This option sets the URL for the jsdom environment. It isreflected in properties such as location.href 
  170.   // testURL: "http://localhost"
  171.  
  172.   // Setting this value to "fake" allows the use offake timers for functions such as "setTimeout" 
  173.   // timers: "real"
  174.  
  175.   // A map from regular expressions to paths to transformers 
  176.   // transform: undefined, 
  177.  
  178.   // An array of regexp pattern strings that are matched againstall source file paths, matched files will skip transformation 
  179.   // transformIgnorePatterns: [ 
  180.   //  "/node_modules/"
  181.   //  "\\.pnp\\.[^\\/]+$" 
  182.   // ], 
  183.  
  184.   // An array of regexp pattern strings that are matched againstall modules before the module loader will automatically return a mock for them 
  185.   // unmockedModulePathPatterns: undefined, 
  186.  
  187.   // Indicates whether each individual test should be reportedduring the run 
  188.   // verbose: undefined, 
  189.  
  190.   // An array of regexp patterns that are matched against allsource file paths before re-running tests in watch mode 
  191.   // watchPathIgnorePatterns: [], 
  192.  
  193.   // Whether to use watchman for file crawling 
  194.   // watchman: true
  195. }; 

Jest CLI Options

参考:https://jestjs.io/zh-Hans/docs/cli

指定测试文件运行

  1. "scripts":{ 
  2.    "test":"jest ./math.test.js" 
  3.  }, 

Jest 监视模式

--watchAll 选项:监视文件的更改并在任何更改时重新运行所有测试。

  1. "scripts": { 
  2.   "test""jest --watchAll" 
  3.  }, 

Jest API

在测试文件中,Jest 将所有这些方法和对象放入全局环境中。无需要求或导入任何内容即可使用它们。但是,如果喜欢显式导入,则可以:

  1. import { describe, expect, test } from'@jest/globals' 

Test 函数

test 函数别名:it(name, fn, timeout)。

  • test(name,fn, timeout)
  • test.concurrent(name, fn, timeout)
  • test.concurrent.each(table)(name, fn, timeout)
  • test.concurrent.only.each(table)(name, fn)
  • test.concurrent.skip.each(table)(name, fn)
  • test.each(table)(name, fn, timeout)
  • test.only(name, fn, timeout)

只运行当前测试用例

  • test.only.each(table)(name, fn)
  • test.skip(name,fn)
  • test.skip.each(table)(name, fn)
  • test.todo(name)

创建 global-api.test.js 测试文件,注意,测试文件中必须有一个测试用例,如果没有则直接报错。

  1. test('should ', () => { 
  2.   console.log('test--api'
  3. }) 
  1. test('should ', () => { 
  2.   console.log('test--api'
  3. }) 
  4. test('should1 ', () => { 
  5.   console.log('test--api1'
  6. }) 
  7.  
  8. // 上面两个不运行 
  9. test.only('should2 ', () => { 
  10.   console.log('test--api2'
  11. }) 

Expect 匹配器

在编写测试时,通常需要检查值是否满足某些条件。Expect 让我们可以访问许多“匹配器”,以验证不同的内容。

  1. test('two plus two is four', () => { 
  2.   expect(2+2).toBe(6) 
  3.   expect({ name:'jack' }).toEqual({ name:'jack' }) 
  4.   expect('Christoph').toMatch(/stop/) 
  5.   expect(4).toBeGreaterThan(3) 
  6.   expect(4).toBeLessThan(5) 
  7. }) 

完整的匹配器列表查看:https://jestjs.io/zh-Hans/docs/expect

describe 函数

describe 创建一个将几个相关测试组合在一起的块。

  1. const myBeverage = { 
  2.   delicious:true
  3.   sour:false
  4. }; 
  5.  
  6. describe('my beverage', () => { 
  7.   test('is delicious', () => { 
  8.     expect(myBeverage.delicious).toBeTruthy(); 
  9.   }); 
  10.  
  11.   test('is not sour', () => { 
  12.     expect(myBeverage.sour).toBeFalsy(); 
  13.   }); 
  14. }); 

分组最直观的就是在测试提示中,有更加友好的信息输出。

  • describe(name,fn)
  • describe.each(table)(name, fn, timeout)
  • describe.only(name,fn)
  • describe.only.each(table)(name, fn)
  • describe.skip(name,fn)
  • describe.skip.each(table)(name, fn)

 

责任编辑:姜华 来源: 勾勾的前端世界
相关推荐

2023-05-18 14:01:00

前端自动化测试

2021-06-30 19:48:21

前端自动化测试Vue 应用

2021-06-25 10:57:30

前端自动化测试开发

2009-08-19 09:00:48

单元测试框架自动化测试

2017-12-24 21:00:10

自动化测试测试框架敏捷

2011-04-18 12:52:37

自动化测试功能测试软件测试

2022-09-14 10:00:12

前端自动化测试

2016-09-26 16:42:19

JavaScript前端单元测试

2020-04-28 09:00:00

测试测试自动化

2020-09-14 07:00:00

测试自动化框架

2023-10-12 07:40:54

Minium自动化框架

2011-06-03 17:06:09

自动化测试

2019-04-18 09:00:00

Java自动化测试框架

2023-11-08 13:18:00

JestJavaScript框架

2011-12-23 17:09:57

自动化测试

2012-12-24 22:54:31

2014-04-16 14:15:01

QCon2014

2010-09-08 15:25:09

自动化测试技术网站链接测试

2011-08-16 15:36:47

iPhone应用测试

2021-07-02 17:22:50

前端TDDBDD
点赞
收藏

51CTO技术栈公众号