99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Jest 對象API

2021-09-23 20:23 更新

該jest對象自動在每個測試文件的范圍內(nèi)。jest對象中的方法有助于創(chuàng)建模擬并讓你控制 Jest 的整體行為。它也可以通過 via 顯式導(dǎo)入?import {jest} from '@jest/globals?'。

模擬模塊

jest.disableAutomock()

在模塊加載器中禁用自動模擬。

有關(guān)更多信息,請參閱配置automock部分

調(diào)用此方法后,所有require()s 將返回每個模塊的真實版本(而不是模擬版本)。

有配置:

  1. {
  2. "automock": true
  3. }

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. };
  1. // __tests__/disableAutomocking.js
  2. import utils from '../utils';
  3. jest.disableAutomock();
  4. test('original implementation', () => {
  5. // now we have the original implementation,
  6. // even if we set the automocking in a jest configuration
  7. expect(utils.authorize()).toBe('token');
  8. });

當(dāng)你要模擬的依賴項數(shù)量遠小于你不模擬的依賴項數(shù)量時,這通常很有用。例如,如果你正在為使用大量依賴項的模塊編寫測試,這些依賴項可以合理地歸類為模塊的“實現(xiàn)細節(jié)”,那么你可能不想模擬它們。

可能被視為“實現(xiàn)細節(jié)”的依賴項示例包括從語言內(nèi)置(例如 ?Array.prototype? 方法)到高度通用的實用程序方法(例如下劃線?/lo-dash?、數(shù)組實用程序等)和整個庫(如 ?React?)。 ?js?。

返回jest用于鏈接的對象。

注意:此方法以前稱為?autoMockOff.? 使用時?babel-jest?,對?disableAutomock?的調(diào)用會自動提升到代碼塊的頂部。使用?autoMockOff?,如果你想明確地避免這種行為。

jest.enableAutomock()

在模塊加載器中啟用自動模擬。

返回jest用于鏈接的對象。

有關(guān)更多信息,請參閱配置automock部分

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. isAuthorized: secret => secret === 'wizard',
  7. };
  1. // __tests__/enableAutomocking.js
  2. jest.enableAutomock();
  3. import utils from '../utils';
  4. test('original implementation', () => {
  5. // now we have the mocked implementation,
  6. expect(utils.authorize._isMockFunction).toBeTruthy();
  7. expect(utils.isAuthorized._isMockFunction).toBeTruthy();
  8. });

注意:此方法以前稱為?autoMockOn?. 使用時?babel-jest?,對 的調(diào)用?enableAutomock?會自動提升到代碼塊的頂部。使用?autoMockOn?,如果你想明確地避免這種行為。

jest.createMockFromModule(moduleName)

在 Is 26.0.0+ 中重命名

同樣在別名下: ?.genMockFromModule(moduleName)?

給定模塊的名稱,使用自動模擬系統(tǒng)為你生成模塊的模擬版本。

當(dāng)你想要創(chuàng)建擴展自動模擬行為的手動模擬時,這很有用。

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. isAuthorized: secret => secret === 'wizard',
  7. };
  1. // __tests__/createMockFromModule.test.js
  2. const utils = jest.createMockFromModule('../utils').default;
  3. utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
  4. test('implementation created by jest.createMockFromModule', () => {
  5. expect(utils.authorize.mock).toBeTruthy();
  6. expect(utils.isAuthorized('not wizard')).toEqual(true);
  7. });

這是?createMockFromModule?模擬以下數(shù)據(jù)類型的方式:

函數(shù) Function

創(chuàng)建一個新的模擬函數(shù)。新函數(shù)沒有形式參數(shù),調(diào)用時將返回?undefined?。此功能也適用于?async?函數(shù)。

類 Class

創(chuàng)建一個新類。原始類的接口被保留,所有的類成員函數(shù)和屬性都將被模擬。

對象 Object

創(chuàng)建一個新的深度克隆對象。對象鍵被維護并且它們的值被模擬。

數(shù)組 Array

創(chuàng)建一個新的空數(shù)組,忽略原始數(shù)組。

屬性 Primitives

創(chuàng)建一個與原始屬性具有相同原始值的新屬性。

示例:

  1. // example.js
  2. module.exports = {
  3. function: function square(a, b) {
  4. return a * b;
  5. },
  6. asyncFunction: async function asyncSquare(a, b) {
  7. const result = await a * b;
  8. return result;
  9. },
  10. class: new class Bar {
  11. constructor() {
  12. this.array = [1, 2, 3];
  13. }
  14. foo() {}
  15. },
  16. object: {
  17. baz: 'foo',
  18. bar: {
  19. fiz: 1,
  20. buzz: [1, 2, 3],
  21. },
  22. },
  23. array: [1, 2, 3],
  24. number: 123,
  25. string: 'baz',
  26. boolean: true,
  27. symbol: Symbol.for('a.b.c'),
  28. };
  1. // __tests__/example.test.js
  2. const example = jest.createMockFromModule('./example');
  3. test('should run example code', () => {
  4. // creates a new mocked function with no formal arguments.
  5. expect(example.function.name).toEqual('square');
  6. expect(example.function.length).toEqual(0);
  7. // async functions get the same treatment as standard synchronous functions.
  8. expect(example.asyncFunction.name).toEqual('asyncSquare');
  9. expect(example.asyncFunction.length).toEqual(0);
  10. // creates a new class with the same interface, member functions and properties are mocked.
  11. expect(example.class.constructor.name).toEqual('Bar');
  12. expect(example.class.foo.name).toEqual('foo');
  13. expect(example.class.array.length).toEqual(0);
  14. // creates a deeply cloned version of the original object.
  15. expect(example.object).toEqual({
  16. baz: 'foo',
  17. bar: {
  18. fiz: 1,
  19. buzz: [],
  20. },
  21. });
  22. // creates a new empty array, ignoring the original array.
  23. expect(example.array.length).toEqual(0);
  24. // creates a new property with the same primitive value as the original property.
  25. expect(example.number).toEqual(123);
  26. expect(example.string).toEqual('baz');
  27. expect(example.boolean).toEqual(true);
  28. expect(example.symbol).toEqual(Symbol.for('a.b.c'));
  29. });

jest.mock(moduleName, factory, options)

在需要時使用自動模擬版本模擬模塊。?factory?并且?options?是可選的。例如:

  1. // banana.js
  2. module.exports = () => 'banana';
  3. // __tests__/test.js
  4. jest.mock('../banana');
  5. const banana = require('../banana'); // banana will be explicitly mocked.
  6. banana(); // will return 'undefined' because the function is auto-mocked.

第二個參數(shù)可用于指定正在運行的顯式模塊工廠,而不是使用 Jest 的自動模擬功能:

  1. jest.mock('../moduleName', () => {
  2. return jest.fn(() => 42);
  3. });
  4. // This runs the function specified as second argument to `jest.mock`.
  5. const moduleName = require('../moduleName');
  6. moduleName(); // Will return '42';

將?factory?參數(shù)用于具有默認導(dǎo)出的 ES6 模塊時,?__esModule: true?需要指定該屬性。該屬性一般由 ?Babel/TypeScript? 生成,但這里需要手動設(shè)置。導(dǎo)入默認導(dǎo)出時,是導(dǎo)入?default?從導(dǎo)出對象命名的屬性的指令:

  1. import moduleName, {foo} from '../moduleName';
  2. jest.mock('../moduleName', () => {
  3. return {
  4. __esModule: true,
  5. default: jest.fn(() => 42),
  6. foo: jest.fn(() => 43),
  7. };
  8. });
  9. moduleName(); // Will return 42
  10. foo(); // Will return 43

第三個參數(shù)可用于創(chuàng)建虛擬模擬——系統(tǒng)中不存在的模塊的模擬:

  1. jest.mock(
  2. '../moduleName',
  3. () => {
  4. /*
  5. * Custom implementation of a module that doesn't exist in JS,
  6. * like a generated module or a native module in react-native.
  7. */
  8. },
  9. {virtual: true},
  10. );
警告:在安裝文件(由 指定?setupTestFrameworkScriptFile?)中導(dǎo)入模塊將阻止對相關(guān)模塊及其導(dǎo)入的所有模塊進行模擬。

被模擬的模塊jest.mock僅針對調(diào)用jest.mock. 另一個導(dǎo)入模塊的文件將獲得原始實現(xiàn),即使它在模擬模塊的測試文件之后運行。

返回jest用于鏈接的對象。

jest.unmock(moduleName)

指示模塊系統(tǒng)不應(yīng)返回指定模塊的模擬版本?require()?(例如,它應(yīng)始終返回真實模塊)。

此 API 最常見的用途是指定給定測試打算測試的模塊(因此不想自動模擬)。

返回jest用于鏈接的對象。

jest.doMock(moduleName, factory, options)

使用時?babel-jest?,對 的調(diào)用?mock?會自動提升到代碼塊的頂部。如果你想明確避免這種行為,請使用此方法。

一個有用的例子是當(dāng)你想在同一個文件中以不同的方式模擬一個模塊時:

  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('moduleName 1', () => {
  5. jest.doMock('../moduleName', () => {
  6. return jest.fn(() => 1);
  7. });
  8. const moduleName = require('../moduleName');
  9. expect(moduleName()).toEqual(1);
  10. });
  11. test('moduleName 2', () => {
  12. jest.doMock('../moduleName', () => {
  13. return jest.fn(() => 2);
  14. });
  15. const moduleName = require('../moduleName');
  16. expect(moduleName()).toEqual(2);
  17. });

?jest.doMock()?與 ES6 導(dǎo)入一起使用需要額外的步驟。如果你不想?require?在測試中使用,請遵循以下步驟:

  • 我們必須指定?__esModule: true屬性?(jest.mock()有關(guān)更多信息,請參閱API)。
  • 靜態(tài) ES6 模塊導(dǎo)入被提升到文件的頂部,因此我們必須使用import().
  • 最后,我們需要一個支持動態(tài)導(dǎo)入的環(huán)境。請參閱使用 Babel進行初始設(shè)置。然后將插件babel-plugin-dynamic-import-node或等效插件添加到你的 Babel 配置中以啟用 Node.js 中的動態(tài)導(dǎo)入。
  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('moduleName 1', () => {
  5. jest.doMock('../moduleName', () => {
  6. return {
  7. __esModule: true,
  8. default: 'default1',
  9. foo: 'foo1',
  10. };
  11. });
  12. return import('../moduleName').then(moduleName => {
  13. expect(moduleName.default).toEqual('default1');
  14. expect(moduleName.foo).toEqual('foo1');
  15. });
  16. });
  17. test('moduleName 2', () => {
  18. jest.doMock('../moduleName', () => {
  19. return {
  20. __esModule: true,
  21. default: 'default2',
  22. foo: 'foo2',
  23. };
  24. });
  25. return import('../moduleName').then(moduleName => {
  26. expect(moduleName.default).toEqual('default2');
  27. expect(moduleName.foo).toEqual('foo2');
  28. });
  29. });

返回jest用于鏈接的對象。

jest.dontMock(moduleName)

使用時?babel-jest?,對 的調(diào)用?unmock?會自動提升到代碼塊的頂部。如果你想明確避免這種行為,請使用此方法。

返回jest用于鏈接的對象。

jest.setMock(moduleName, moduleExports)

顯式提供模塊系統(tǒng)應(yīng)為指定模塊返回的模擬對象。

有時,模塊系統(tǒng)通常為你提供的自動生成的模擬有時不足以滿足你的測試需求。通常在這些情況下,你應(yīng)該編寫一個更適合相關(guān)模塊的手動模擬。但是,在極少數(shù)情況下,即使是手動模擬也不適合你的目的,你需要在測試中自己構(gòu)建模擬。

在這些罕見的情況下,你可以使用此 API 手動填充模塊系統(tǒng)的模擬模塊注冊表中的插槽。

返回jest用于鏈接的對象。

注意 建議jest.mock()改用。該jest.mockAPI的第二個參數(shù)是一個模塊工廠,而不是預(yù)期輸出模塊對象。

jest.requireActual(moduleName)

返回實際模塊而不是模擬,繞過對模塊是否應(yīng)接收模擬實現(xiàn)的所有檢查。

示例:

  1. jest.mock('../myModule', () => {
  2. // Require the original module to not be mocked...
  3. const originalModule = jest.requireActual('../myModule');
  4. return {
  5. __esModule: true, // Use it when dealing with esModules
  6. ...originalModule,
  7. getRandom: jest.fn().mockReturnValue(10),
  8. };
  9. });
  10. const getRandom = require('../myModule').getRandom;
  11. getRandom(); // Always returns 10

jest.requireMock(moduleName)

返回一個模擬模塊而不是實際模塊,繞過對模塊是否應(yīng)該正常需要的所有檢查。

jest.resetModules()

重置模塊注冊表 - 所有必需模塊的緩存。這對于隔離本地狀態(tài)可能在測試之間發(fā)生沖突的模塊很有用。

示例:

  1. const sum1 = require('../sum');
  2. jest.resetModules();
  3. const sum2 = require('../sum');
  4. sum1 === sum2;
  5. // > false (Both sum modules are separate "instances" of the sum module.)

測試中的示例:

  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('works', () => {
  5. const sum = require('../sum');
  6. });
  7. test('works too', () => {
  8. const sum = require('../sum');
  9. // sum is a different copy of the sum module from the previous test.
  10. });

返回jest用于鏈接的對象。

jest.isolateModules(fn)

?jest.isolateModules(fn)?比?jest.resetModules()?為回調(diào)函數(shù)中加載的模塊創(chuàng)建沙箱注冊表更進一步。這對于隔離每個測試的特定模塊非常有用,這樣本地模塊狀態(tài)就不會在測試之間發(fā)生沖突。

  1. let myModule;
  2. jest.isolateModules(() => {
  3. myModule = require('myModule');
  4. });
  5. const otherCopyOfMyModule = require('myModule');

模擬功能

jest.fn(implementation)

返回一個新的、未使用的模擬函數(shù)??蛇x地采用模擬實現(xiàn)。

  1. const mockFn = jest.fn();
  2. mockFn();
  3. expect(mockFn).toHaveBeenCalled();
  4. // With a mock implementation:
  5. const returnsTrue = jest.fn(() => true);
  6. console.log(returnsTrue()); // true;

jest.isMockFunction(fn)

確定給定的函數(shù)是否是模擬函數(shù)。

jest.spyOn(object, methodName)

創(chuàng)建一個類似于?jest.fn?但也跟蹤對 的調(diào)用的模擬函數(shù)?object[methodName]?。返回一個 Jest模擬函數(shù)。

注意:默認情況下,?jest.spyOn?也會調(diào)用?spied?方法。這是與大多數(shù)其他測試庫不同的行為。如果你想覆蓋原來的功能,你可以使用?jest.spyOn(object, methodName).mockImplementation(() => customImplementation)?或?object[methodName] = jest.fn(() => customImplementation);?

示例:

  1. const video = {
  2. play() {
  3. return true;
  4. },
  5. };
  6. module.exports = video;

示例測試:

  1. const video = require('./video');
  2. test('plays video', () => {
  3. const spy = jest.spyOn(video, 'play');
  4. const isPlaying = video.play();
  5. expect(spy).toHaveBeenCalled();
  6. expect(isPlaying).toBe(true);
  7. spy.mockRestore();
  8. });

jest.spyOn(object, methodName, accessType?)

Jest 22.1.0+ 開始,該?jest.spyOn?方法采用可選的第三個參數(shù)?accessType?,可以是?'get??或?'set'?,這在你想分別監(jiān)視 ?getter ?或 ?setter ?時被證明是有用的。

示例:

  1. const video = {
  2. // it's a getter!
  3. get play() {
  4. return true;
  5. },
  6. };
  7. module.exports = video;
  8. const audio = {
  9. _volume: false,
  10. // it's a setter!
  11. set volume(value) {
  12. this._volume = value;
  13. },
  14. get volume() {
  15. return this._volume;
  16. },
  17. };
  18. module.exports = audio;

示例測試:

  1. const video = require('./video');
  2. test('plays video', () => {
  3. const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'
  4. const isPlaying = video.play;
  5. expect(spy).toHaveBeenCalled();
  6. expect(isPlaying).toBe(true);
  7. spy.mockRestore();
  8. });
  9. const audio = require('./audio');
  10. test('plays audio', () => {
  11. const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'
  12. audio.volume = 100;
  13. expect(spy).toHaveBeenCalled();
  14. expect(audio.volume).toBe(100);
  15. spy.mockRestore();
  16. });

jest.clearAllMocks()

清除所有模擬的mock.calls和mock.instances屬性。相當(dāng)于調(diào)用.mockClear()每個模擬函數(shù)。

返回jest用于鏈接的對象。

jest.resetAllMocks()

重置所有模擬的狀態(tài)。相當(dāng)于調(diào)用.mockReset()每個模擬函數(shù)。

返回jest用于鏈接的對象。

jest.restoreAllMocks()

將所有模擬恢復(fù)到其原始值。相當(dāng)于調(diào)用.mockRestore()每個模擬函數(shù)。請注意,jest.restoreAllMocks()只有在使用jest.spyOn;創(chuàng)建模擬時才有效;其他模擬將要求你手動恢復(fù)它們。

模擬計時器

jest.useFakeTimers(implementation?: 'modern' | 'legacy')

指示玩笑使用的標(biāo)準(zhǔn)定時器功能假版本(setTimeout,setInterval,clearTimeout,clearInterval,nextTick,setImmediate和clearImmediate)。

如果你'modern'作為參數(shù)傳遞,@sinonjs/fake-timers將用作實現(xiàn)而不是 Jest 自己的假計時器。這也模擬了額外的計時器,如Date. 'modern'將是 Jest 27 中的默認行為。

返回jest用于鏈接的對象。

jest.useRealTimers()

指示 Jest 使用標(biāo)準(zhǔn)計時器函數(shù)的真實版本。

返回jest用于鏈接的對象。

jest.runAllTicks()

廢氣的微-task隊列(通常在節(jié)點經(jīng)由接口?process.nextTick?)。

調(diào)用此 API 時,所有已通過排隊的待處理微任務(wù)process.nextTick將被執(zhí)行。此外,如果這些微任務(wù)自己調(diào)度新的微任務(wù),這些微任務(wù)將不斷耗盡,直到隊列中沒有更多的微任務(wù)。

jest.runAllTimers()

廢氣兩者宏-task隊列(即,所有的任務(wù)排隊通過setTimeout(),setInterval()和setImmediate())和微-task隊列(通常在節(jié)點經(jīng)由接口?process.nextTick?)。

調(diào)用此 API 時,將執(zhí)行所有未決的宏任務(wù)和微任務(wù)。如果這些任務(wù)自己安排了新任務(wù),那么這些任務(wù)將不斷耗盡,直到隊列中沒有剩余任務(wù)為止。

這對于在測試期間同步執(zhí)行 setTimeouts 通常很有用,以便同步斷言某些僅在執(zhí)行?setTimeout()?或?setInterval()?回調(diào)后才會發(fā)生的行為。有關(guān)更多信息,請參閱計時器模擬文檔。

jest.runAllImmediates()

耗盡排隊的所有任務(wù)?setImmediate()?。

注意:使用現(xiàn)代偽定時器實現(xiàn)時,此功能不可用

jest.advanceTimersByTime(msToRun)

在 Is 22.0.0+ 中重命名

同樣在別名下: .runTimersToTime()

只執(zhí)行宏任務(wù)隊列(即所有由?setTimeout()orsetInterval()?和排隊的任務(wù)?setImmediate()?)。

調(diào)用此 API 時,所有計時器都會提前?msToRun?幾毫秒。所有已通過?setTimeout()?或排隊?setInterval()?并在此時間范圍內(nèi)執(zhí)行的未決“宏任務(wù)”都將被執(zhí)行。此外,如果這些宏任務(wù)調(diào)度將在同一時間范圍內(nèi)執(zhí)行的新宏任務(wù),則這些宏任務(wù)將被執(zhí)行,直到隊列中沒有更多宏任務(wù)剩余,這應(yīng)該在?msToRun?幾毫秒內(nèi)運行。

jest.runOnlyPendingTimers()

僅執(zhí)行當(dāng)前掛起的宏任務(wù)(即,僅執(zhí)行已排隊?setTimeout()?或?setInterval()?到此為止的任務(wù))。如果任何當(dāng)前掛起的宏任務(wù)調(diào)度新的宏任務(wù),則該調(diào)用將不會執(zhí)行這些新任務(wù)。

這對于諸如被測試模塊調(diào)度 ?asetTimeout()?其回調(diào)以?setTimeout()?遞歸方式調(diào)度另一個(意味著調(diào)度永不停止)的場景很有用。在這些情況下,能夠一次一步向前運行是很有用的。

jest.advanceTimersToNextTimer(steps)

將所有計時器提前所需的毫秒數(shù),以便僅運行下一個超時/間隔。

或者,你可以提供steps,因此它將運行steps下一次超時/間隔的數(shù)量。

jest.clearAllTimers()

從計時器系統(tǒng)中刪除任何掛起的計時器。

這意味著,如果任何計時器已被調(diào)度(但尚未執(zhí)行),它們將被清除并且將來永遠沒有機會執(zhí)行。

jest.getTimerCount()

返回仍要運行的假計時器的數(shù)量。

jest.setSystemTime(now?: number | Date)

設(shè)置假定時器使用的當(dāng)前系統(tǒng)時間。模擬用戶在程序運行時更改系統(tǒng)時鐘。它會影響當(dāng)前時間,但它本身不會導(dǎo)致例如定時器觸發(fā);他們將完全按照沒有調(diào)用?jest.setSystemTime()?.

注意:此功能僅在使用現(xiàn)代偽計時器實現(xiàn)時可用

jest.getRealSystemTime()

當(dāng)?mocking?的時候,??Date.now()??也會被?mock? 。如果你出于某種原因需要訪問實時當(dāng)前時間,你可以調(diào)用此函數(shù)。

注意:此功能僅在使用現(xiàn)代偽計時器實現(xiàn)時可用

雜項

jest.setTimeout(timeout)

以毫秒為單位設(shè)置測試和掛鉤之前/之后的默認超時間隔。這僅影響調(diào)用此函數(shù)的測試文件。

注意:如果不調(diào)用此方法,默認超時間隔為 5 秒。

注意:如果你想為所有測試文件設(shè)置超時,一個很好的地方是在?setupFilesAfterEnv?.

示例:

  1. jest.setTimeout(1000); // 1 second

jest.retryTimes()

運行失敗的測試 n 次,直到它們通過或直到用盡最大重試次數(shù)。這只適用于jest-circus!

測試中的示例:

  1. jest.retryTimes(3);
  2. test('will fail', () => {
  3. expect(true).toBe(false);
  4. });

返回jest用于鏈接的對象。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號