日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
前端自動(dòng)化測(cè)試:Jest測(cè)試框架應(yīng)用

Jest : https://jestjs.io/zh-Hans/是 Facebook 出品的一個(gè) JavaScript 開(kāi)源測(cè)試框架。

相對(duì)其他測(cè)試框架,其一大特點(diǎn)就是就是內(nèi)置了常用的測(cè)試工具,比如零配置、自帶斷言、測(cè)試覆蓋率工具等功能,實(shí)現(xiàn)了開(kāi)箱即用。

Jest 適用但不局限于使用以下技術(shù)的項(xiàng)目:Babel、TypeScript、 Node、 React、Angular、Vue 等。

Jest 主要特點(diǎn):

  • 零配置
  • 自帶斷言
  • 作為一個(gè)面向前端的測(cè)試框架, Jest 可以利用其特有的快照測(cè)試功能,通過(guò)比對(duì)UI 代碼生成的快照文件,實(shí)現(xiàn)對(duì) React 等常見(jiàn)前端框架的自動(dòng)測(cè)試。
  • Jest 的測(cè)試用例是并行執(zhí)行的,而且只執(zhí)行發(fā)生改變的文件所對(duì)應(yīng)的測(cè)試,提升了測(cè)試速度。
  • 測(cè)試覆蓋率
  • Mock 模擬

快速體驗(yàn) Jest

安裝 Jest 到項(xiàng)目中:

 
 
 
  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('測(cè)試加法', () => { 
  5.   expect(add(1,2)).toBe(3) 
  6. }) 
  7.  
  8. test('測(cè)試減法', () => { 
  9.   expect(subtract(2,1)).toBe(1) 
  10. }) 
 
 
 
  1. //package.json 
  2.   "scripts":{ 
  3.     "test":"jest" 
  4.   } 

jest 命令會(huì)運(yùn)行項(xiàng)目中所有以 .test.js 結(jié)尾的文件

最后運(yùn)行測(cè)試命令:

 
 
 
  1. npm run test 

解析:

  • jest 找到項(xiàng)目中所有以 .test.js 結(jié)尾的文件并運(yùn)行
  • jest 會(huì)給測(cè)試文件提供 test、expect 等全局函數(shù),所以在測(cè)試文件中可以直接使用
  • jest 為測(cè)試結(jié)果提供了良好的日志輸出

解決 vscode 中 jest 代碼提示問(wèn)題

 
 
 
  1. npm i -D @types/jest 

注意:@types/jest 必須安裝到項(xiàng)目的根目錄,并且以根目錄的方式在 vscode 中打開(kāi),否則不生效。或者說(shuō)只要是 vscode 打開(kāi)的項(xiàng)目根目錄有 @types/jest 這個(gè)包就可以了。

配置文件

 
 
 
  1. npx jest--init 

配置文件生成選項(xiàng):

  • 是否使用 ts ;
  • 使用哪種測(cè)試環(huán)境;
  • 使用 jest 收集測(cè)試覆蓋率報(bào)告;
  • 使用那種引擎檢測(cè)覆蓋率:v8 處于實(shí)驗(yàn)性階段,建議 Node v14 后使用,babel 較為成熟
  • 每次測(cè)試時(shí),是否自動(dòng)清除 mock 實(shí)例;

詳細(xì)配置信息參考: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.   // 自動(dòng) mock 所有導(dǎo)入的外部模塊 
  9.   // automock: false, 
  10.  
  11.   // 在指定次數(shù)失敗后停止運(yùn)行測(cè)試 
  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.   // 在每個(gè)測(cè)試之間自動(dòng)清除 mock 調(diào)用和實(shí)例 
  18.   clearMocks:true, 
  19.  
  20.   // 是否收集測(cè)試覆蓋率信息 
  21.   // collectCoverage: false, 
  22.  
  23.   // 一個(gè) glob 模式數(shù)組,指示應(yīng)該為其收集覆蓋率信息的一組文件 
  24.   // collectCoverageFrom: undefined, 
  25.  
  26.   // 測(cè)試覆蓋率報(bào)錯(cuò)文件輸出的目錄 
  27.   coverageDirectory:"coverage", 
  28.  
  29.   // 忽略測(cè)試覆蓋率統(tǒng)計(jì) 
  30.   // coveragePathIgnorePatterns: [ 
  31.   //  "/node_modules/" 
  32.   // ], 
  33.  
  34.   // 指示應(yīng)該使用哪個(gè)提供程序檢測(cè)代碼的覆蓋率,默認(rèn)是 babel,可選 v8,但是 v8 不太穩(wěn)定,建議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.   //  "
  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

指定測(cè)試文件運(yùn)行

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

Jest 監(jiān)視模式

--watchAll 選項(xiàng):監(jiān)視文件的更改并在任何更改時(shí)重新運(yùn)行所有測(cè)試。

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

Jest API

在測(cè)試文件中,Jest 將所有這些方法和對(duì)象放入全局環(huán)境中。無(wú)需要求或?qū)肴魏蝺?nèi)容即可使用它們。但是,如果喜歡顯式導(dǎo)入,則可以:

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

Test 函數(shù)

test 函數(shù)別名: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)

只運(yùn)行當(dāng)前測(cè)試用例

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

創(chuàng)建 global-api.test.js 測(cè)試文件,注意,測(cè)試文件中必須有一個(gè)測(cè)試用例,如果沒(méi)有則直接報(bào)錯(cuò)。

 
 
 
  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. // 上面兩個(gè)不運(yùn)行 
  9. test.only('should2 ', () => { 
  10.   console.log('test--api2') 
  11. }) 

Expect 匹配器

在編寫(xiě)測(cè)試時(shí),通常需要檢查值是否滿足某些條件。Expect 讓我們可以訪問(wèn)許多“匹配器”,以驗(yàn)證不同的內(nèi)容。

 
 
 
  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 函數(shù)

describe 創(chuàng)建一個(gè)將幾個(gè)相關(guān)測(cè)試組合在一起的塊。

 
 
 
  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. }); 

分組最直觀的就是在測(cè)試提示中,有更加友好的信息輸出。

  • 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)

本文標(biāo)題:前端自動(dòng)化測(cè)試:Jest測(cè)試框架應(yīng)用
鏈接分享:http://m.5511xx.com/article/dpicdpp.html