jest.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. */
  9. // Modified from https://raw.githubusercontent.com/flow-typed/flow-typed/master/definitions/npm/jest_v23.x.x/flow_v0.39.x-v0.103.x/jest_v23.x.x.js
  10. // List of modifications:
  11. // - fix some [] -> Array lint warnings
  12. // - make it.each/describe.each take $ReadOnlyArray instead of Array<mixed>
  13. // - added definition for `isolateModules`
  14. //
  15. // TODO(T35016336) remove the .each modifications if flow-typed adopts them
  16. type JestMockFn<TArguments: $ReadOnlyArray<mixed>, TReturn> = {|
  17. (...args: TArguments): TReturn,
  18. /**
  19. * An object for introspecting mock calls
  20. */
  21. mock: {
  22. /**
  23. * An array that represents all calls that have been made into this mock
  24. * function. Each call is represented by an array of arguments that were
  25. * passed during the call.
  26. */
  27. calls: Array<TArguments>,
  28. /**
  29. * An array that contains all the object instances that have been
  30. * instantiated from this mock function.
  31. */
  32. instances: Array<TReturn>,
  33. /**
  34. * An array that contains all the object results that have been
  35. * returned by this mock function call
  36. */
  37. results: Array<{isThrow: boolean, value: TReturn, ...}>,
  38. ...
  39. },
  40. /**
  41. * Resets all information stored in the mockFn.mock.calls and
  42. * mockFn.mock.instances arrays. Often this is useful when you want to clean
  43. * up a mock's usage data between two assertions.
  44. */
  45. mockClear(): void,
  46. /**
  47. * Resets all information stored in the mock. This is useful when you want to
  48. * completely restore a mock back to its initial state.
  49. */
  50. mockReset(): void,
  51. /**
  52. * Removes the mock and restores the initial implementation. This is useful
  53. * when you want to mock functions in certain test cases and restore the
  54. * original implementation in others. Beware that mockFn.mockRestore only
  55. * works when mock was created with jest.spyOn. Thus you have to take care of
  56. * restoration yourself when manually assigning jest.fn().
  57. */
  58. mockRestore(): void,
  59. /**
  60. * Accepts a function that should be used as the implementation of the mock.
  61. * The mock itself will still record all calls that go into and instances
  62. * that come from itself -- the only difference is that the implementation
  63. * will also be executed when the mock is called.
  64. */
  65. mockImplementation(
  66. fn: (...args: TArguments) => TReturn,
  67. ): JestMockFn<TArguments, TReturn>,
  68. /**
  69. * Accepts a function that will be used as an implementation of the mock for
  70. * one call to the mocked function. Can be chained so that multiple function
  71. * calls produce different results.
  72. */
  73. mockImplementationOnce(
  74. fn: (...args: TArguments) => TReturn,
  75. ): JestMockFn<TArguments, TReturn>,
  76. /**
  77. * Accepts a string to use in test result output in place of "jest.fn()" to
  78. * indicate which mock function is being referenced.
  79. */
  80. mockName(name: string): JestMockFn<TArguments, TReturn>,
  81. /**
  82. * Just a simple sugar function for returning `this`
  83. */
  84. mockReturnThis(): void,
  85. /**
  86. * Accepts a value that will be returned whenever the mock function is called.
  87. */
  88. mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,
  89. /**
  90. * Sugar for only returning a value once inside your mock
  91. */
  92. mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>,
  93. /**
  94. * Sugar for jest.fn().mockImplementation(() => Promise.resolve(value))
  95. */
  96. mockResolvedValue(value: TReturn): JestMockFn<TArguments, Promise<TReturn>>,
  97. /**
  98. * Sugar for jest.fn().mockImplementationOnce(() => Promise.resolve(value))
  99. */
  100. mockResolvedValueOnce(
  101. value: TReturn,
  102. ): JestMockFn<TArguments, Promise<TReturn>>,
  103. /**
  104. * Sugar for jest.fn().mockImplementation(() => Promise.reject(value))
  105. */
  106. mockRejectedValue(value: TReturn): JestMockFn<TArguments, Promise<any>>,
  107. /**
  108. * Sugar for jest.fn().mockImplementationOnce(() => Promise.reject(value))
  109. */
  110. mockRejectedValueOnce(value: TReturn): JestMockFn<TArguments, Promise<any>>,
  111. |};
  112. type JestAsymmetricEqualityType = {
  113. /**
  114. * A custom Jasmine equality tester
  115. */
  116. asymmetricMatch(value: mixed): boolean,
  117. ...
  118. };
  119. type JestCallsType = {
  120. allArgs(): mixed,
  121. all(): mixed,
  122. any(): boolean,
  123. count(): number,
  124. first(): mixed,
  125. mostRecent(): mixed,
  126. reset(): void,
  127. ...
  128. };
  129. type JestClockType = {
  130. install(): void,
  131. mockDate(date: Date): void,
  132. tick(milliseconds?: number): void,
  133. uninstall(): void,
  134. ...
  135. };
  136. type JestMatcherResult = {
  137. message?: string | (() => string),
  138. pass: boolean,
  139. ...
  140. };
  141. type JestMatcher = (
  142. actual: any,
  143. expected: any,
  144. ) => JestMatcherResult | Promise<JestMatcherResult>;
  145. type JestPromiseType = {
  146. /**
  147. * Use rejects to unwrap the reason of a rejected promise so any other
  148. * matcher can be chained. If the promise is fulfilled the assertion fails.
  149. */
  150. rejects: JestExpectType,
  151. /**
  152. * Use resolves to unwrap the value of a fulfilled promise so any other
  153. * matcher can be chained. If the promise is rejected the assertion fails.
  154. */
  155. resolves: JestExpectType,
  156. ...
  157. };
  158. /**
  159. * Jest allows functions and classes to be used as test names in test() and
  160. * describe()
  161. */
  162. type JestTestName = string | Function;
  163. /**
  164. * Plugin: jest-styled-components
  165. */
  166. type JestStyledComponentsMatcherValue =
  167. | string
  168. | JestAsymmetricEqualityType
  169. | RegExp
  170. | typeof undefined;
  171. type JestStyledComponentsMatcherOptions = {
  172. media?: string,
  173. modifier?: string,
  174. supports?: string,
  175. ...
  176. };
  177. type JestStyledComponentsMatchersType = {
  178. toHaveStyleRule(
  179. property: string,
  180. value: JestStyledComponentsMatcherValue,
  181. options?: JestStyledComponentsMatcherOptions,
  182. ): void,
  183. ...
  184. };
  185. /**
  186. * Plugin: jest-enzyme
  187. */
  188. type EnzymeMatchersType = {
  189. toBeChecked(): void,
  190. toBeDisabled(): void,
  191. toBeEmpty(): void,
  192. toBeEmptyRender(): void,
  193. toBePresent(): void,
  194. toContainReact(element: React$Element<any>): void,
  195. toExist(): void,
  196. toHaveClassName(className: string): void,
  197. toHaveHTML(html: string): void,
  198. toHaveProp: ((propKey: string, propValue?: any) => void) &
  199. ((props: Object) => void),
  200. toHaveRef(refName: string): void,
  201. toHaveState: ((stateKey: string, stateValue?: any) => void) &
  202. ((state: Object) => void),
  203. toHaveStyle: ((styleKey: string, styleValue?: any) => void) &
  204. ((style: Object) => void),
  205. toHaveTagName(tagName: string): void,
  206. toHaveText(text: string): void,
  207. toIncludeText(text: string): void,
  208. toHaveValue(value: any): void,
  209. toMatchElement(element: React$Element<any>): void,
  210. toMatchSelector(selector: string): void,
  211. ...
  212. };
  213. // DOM testing library extensions https://github.com/kentcdodds/dom-testing-library#custom-jest-matchers
  214. type DomTestingLibraryType = {
  215. toBeInTheDOM(): void,
  216. toHaveTextContent(content: string): void,
  217. toHaveAttribute(name: string, expectedValue?: string): void,
  218. ...
  219. };
  220. // Jest JQuery Matchers: https://github.com/unindented/custom-jquery-matchers
  221. type JestJQueryMatchersType = {
  222. toExist(): void,
  223. toHaveLength(len: number): void,
  224. toHaveId(id: string): void,
  225. toHaveClass(className: string): void,
  226. toHaveTag(tag: string): void,
  227. toHaveAttr(key: string, val?: any): void,
  228. toHaveProp(key: string, val?: any): void,
  229. toHaveText(text: string | RegExp): void,
  230. toHaveData(key: string, val?: any): void,
  231. toHaveValue(val: any): void,
  232. toHaveCss(css: {[key: string]: any, ...}): void,
  233. toBeChecked(): void,
  234. toBeDisabled(): void,
  235. toBeEmpty(): void,
  236. toBeHidden(): void,
  237. toBeSelected(): void,
  238. toBeVisible(): void,
  239. toBeFocused(): void,
  240. toBeInDom(): void,
  241. toBeMatchedBy(sel: string): void,
  242. toHaveDescendant(sel: string): void,
  243. toHaveDescendantWithText(sel: string, text: string | RegExp): void,
  244. ...
  245. };
  246. // Jest Extended Matchers: https://github.com/jest-community/jest-extended
  247. type JestExtendedMatchersType = {
  248. /**
  249. * Note: Currently unimplemented
  250. * Passing assertion
  251. *
  252. * @param {String} message
  253. */
  254. // pass(message: string): void;
  255. /**
  256. * Note: Currently unimplemented
  257. * Failing assertion
  258. *
  259. * @param {String} message
  260. */
  261. // fail(message: string): void;
  262. /**
  263. * Use .toBeEmpty when checking if a String '', Array [] or Object {} is empty.
  264. */
  265. toBeEmpty(): void,
  266. /**
  267. * Use .toBeOneOf when checking if a value is a member of a given Array.
  268. * @param {Array.<*>} members
  269. */
  270. toBeOneOf(members: Array<any>): void,
  271. /**
  272. * Use `.toBeNil` when checking a value is `null` or `undefined`.
  273. */
  274. toBeNil(): void,
  275. /**
  276. * Use `.toSatisfy` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean`.
  277. * @param {Function} predicate
  278. */
  279. toSatisfy(predicate: (n: any) => boolean): void,
  280. /**
  281. * Use `.toBeArray` when checking if a value is an `Array`.
  282. */
  283. toBeArray(): void,
  284. /**
  285. * Use `.toBeArrayOfSize` when checking if a value is an `Array` of size x.
  286. * @param {Number} x
  287. */
  288. toBeArrayOfSize(x: number): void,
  289. /**
  290. * Use `.toIncludeAllMembers` when checking if an `Array` contains all of the same members of a given set.
  291. * @param {Array.<*>} members
  292. */
  293. toIncludeAllMembers(members: Array<any>): void,
  294. /**
  295. * Use `.toIncludeAnyMembers` when checking if an `Array` contains any of the members of a given set.
  296. * @param {Array.<*>} members
  297. */
  298. toIncludeAnyMembers(members: Array<any>): void,
  299. /**
  300. * Use `.toSatisfyAll` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean` for all values in an array.
  301. * @param {Function} predicate
  302. */
  303. toSatisfyAll(predicate: (n: any) => boolean): void,
  304. /**
  305. * Use `.toBeBoolean` when checking if a value is a `Boolean`.
  306. */
  307. toBeBoolean(): void,
  308. /**
  309. * Use `.toBeTrue` when checking a value is equal (===) to `true`.
  310. */
  311. toBeTrue(): void,
  312. /**
  313. * Use `.toBeFalse` when checking a value is equal (===) to `false`.
  314. */
  315. toBeFalse(): void,
  316. /**
  317. * Use .toBeDate when checking if a value is a Date.
  318. */
  319. toBeDate(): void,
  320. /**
  321. * Use `.toBeFunction` when checking if a value is a `Function`.
  322. */
  323. toBeFunction(): void,
  324. /**
  325. * Use `.toHaveBeenCalledBefore` when checking if a `Mock` was called before another `Mock`.
  326. *
  327. * Note: Required Jest version >22
  328. * Note: Your mock functions will have to be asynchronous to cause the timestamps inside of Jest to occur in a differentJS event loop, otherwise the mock timestamps will all be the same
  329. *
  330. * @param {Mock} mock
  331. */
  332. toHaveBeenCalledBefore(mock: JestMockFn<any, any>): void,
  333. /**
  334. * Use `.toBeNumber` when checking if a value is a `Number`.
  335. */
  336. toBeNumber(): void,
  337. /**
  338. * Use `.toBeNaN` when checking a value is `NaN`.
  339. */
  340. toBeNaN(): void,
  341. /**
  342. * Use `.toBeFinite` when checking if a value is a `Number`, not `NaN` or `Infinity`.
  343. */
  344. toBeFinite(): void,
  345. /**
  346. * Use `.toBePositive` when checking if a value is a positive `Number`.
  347. */
  348. toBePositive(): void,
  349. /**
  350. * Use `.toBeNegative` when checking if a value is a negative `Number`.
  351. */
  352. toBeNegative(): void,
  353. /**
  354. * Use `.toBeEven` when checking if a value is an even `Number`.
  355. */
  356. toBeEven(): void,
  357. /**
  358. * Use `.toBeOdd` when checking if a value is an odd `Number`.
  359. */
  360. toBeOdd(): void,
  361. /**
  362. * Use `.toBeWithin` when checking if a number is in between the given bounds of: start (inclusive) and end (exclusive).
  363. *
  364. * @param {Number} start
  365. * @param {Number} end
  366. */
  367. toBeWithin(start: number, end: number): void,
  368. /**
  369. * Use `.toBeObject` when checking if a value is an `Object`.
  370. */
  371. toBeObject(): void,
  372. /**
  373. * Use `.toContainKey` when checking if an object contains the provided key.
  374. *
  375. * @param {String} key
  376. */
  377. toContainKey(key: string): void,
  378. /**
  379. * Use `.toContainKeys` when checking if an object has all of the provided keys.
  380. *
  381. * @param {Array.<String>} keys
  382. */
  383. toContainKeys(keys: Array<string>): void,
  384. /**
  385. * Use `.toContainAllKeys` when checking if an object only contains all of the provided keys.
  386. *
  387. * @param {Array.<String>} keys
  388. */
  389. toContainAllKeys(keys: Array<string>): void,
  390. /**
  391. * Use `.toContainAnyKeys` when checking if an object contains at least one of the provided keys.
  392. *
  393. * @param {Array.<String>} keys
  394. */
  395. toContainAnyKeys(keys: Array<string>): void,
  396. /**
  397. * Use `.toContainValue` when checking if an object contains the provided value.
  398. *
  399. * @param {*} value
  400. */
  401. toContainValue(value: any): void,
  402. /**
  403. * Use `.toContainValues` when checking if an object contains all of the provided values.
  404. *
  405. * @param {Array.<*>} values
  406. */
  407. toContainValues(values: Array<any>): void,
  408. /**
  409. * Use `.toContainAllValues` when checking if an object only contains all of the provided values.
  410. *
  411. * @param {Array.<*>} values
  412. */
  413. toContainAllValues(values: Array<any>): void,
  414. /**
  415. * Use `.toContainAnyValues` when checking if an object contains at least one of the provided values.
  416. *
  417. * @param {Array.<*>} values
  418. */
  419. toContainAnyValues(values: Array<any>): void,
  420. /**
  421. * Use `.toContainEntry` when checking if an object contains the provided entry.
  422. *
  423. * @param {Array.<String, String>} entry
  424. */
  425. toContainEntry(entry: [string, string]): void,
  426. /**
  427. * Use `.toContainEntries` when checking if an object contains all of the provided entries.
  428. *
  429. * @param {Array.<Array.<String, String>>} entries
  430. */
  431. toContainEntries(entries: Array<[string, string]>): void,
  432. /**
  433. * Use `.toContainAllEntries` when checking if an object only contains all of the provided entries.
  434. *
  435. * @param {Array.<Array.<String, String>>} entries
  436. */
  437. toContainAllEntries(entries: Array<[string, string]>): void,
  438. /**
  439. * Use `.toContainAnyEntries` when checking if an object contains at least one of the provided entries.
  440. *
  441. * @param {Array.<Array.<String, String>>} entries
  442. */
  443. toContainAnyEntries(entries: Array<[string, string]>): void,
  444. /**
  445. * Use `.toBeExtensible` when checking if an object is extensible.
  446. */
  447. toBeExtensible(): void,
  448. /**
  449. * Use `.toBeFrozen` when checking if an object is frozen.
  450. */
  451. toBeFrozen(): void,
  452. /**
  453. * Use `.toBeSealed` when checking if an object is sealed.
  454. */
  455. toBeSealed(): void,
  456. /**
  457. * Use `.toBeString` when checking if a value is a `String`.
  458. */
  459. toBeString(): void,
  460. /**
  461. * Use `.toEqualCaseInsensitive` when checking if a string is equal (===) to another ignoring the casing of both strings.
  462. *
  463. * @param {String} string
  464. */
  465. toEqualCaseInsensitive(string: string): void,
  466. /**
  467. * Use `.toStartWith` when checking if a `String` starts with a given `String` prefix.
  468. *
  469. * @param {String} prefix
  470. */
  471. toStartWith(prefix: string): void,
  472. /**
  473. * Use `.toEndWith` when checking if a `String` ends with a given `String` suffix.
  474. *
  475. * @param {String} suffix
  476. */
  477. toEndWith(suffix: string): void,
  478. /**
  479. * Use `.toInclude` when checking if a `String` includes the given `String` substring.
  480. *
  481. * @param {String} substring
  482. */
  483. toInclude(substring: string): void,
  484. /**
  485. * Use `.toIncludeRepeated` when checking if a `String` includes the given `String` substring the correct number of times.
  486. *
  487. * @param {String} substring
  488. * @param {Number} times
  489. */
  490. toIncludeRepeated(substring: string, times: number): void,
  491. /**
  492. * Use `.toIncludeMultiple` when checking if a `String` includes all of the given substrings.
  493. *
  494. * @param {Array.<String>} substring
  495. */
  496. toIncludeMultiple(substring: Array<string>): void,
  497. ...
  498. };
  499. interface JestExpectType {
  500. not: JestExpectType &
  501. EnzymeMatchersType &
  502. DomTestingLibraryType &
  503. JestJQueryMatchersType &
  504. JestStyledComponentsMatchersType &
  505. JestExtendedMatchersType;
  506. /**
  507. * If you have a mock function, you can use .lastCalledWith to test what
  508. * arguments it was last called with.
  509. */
  510. lastCalledWith(...args: Array<any>): void;
  511. /**
  512. * toBe just checks that a value is what you expect. It uses === to check
  513. * strict equality.
  514. */
  515. toBe(value: any): void;
  516. /**
  517. * Use .toBeCalledWith to ensure that a mock function was called with
  518. * specific arguments.
  519. */
  520. toBeCalledWith(...args: Array<any>): void;
  521. /**
  522. * Using exact equality with floating point numbers is a bad idea. Rounding
  523. * means that intuitive things fail.
  524. */
  525. toBeCloseTo(num: number, delta: any): void;
  526. /**
  527. * Use .toBeDefined to check that a variable is not undefined.
  528. */
  529. toBeDefined(): void;
  530. /**
  531. * Use .toBeFalsy when you don't care what a value is, you just want to
  532. * ensure a value is false in a boolean context.
  533. */
  534. toBeFalsy(): void;
  535. /**
  536. * To compare floating point numbers, you can use toBeGreaterThan.
  537. */
  538. toBeGreaterThan(number: number): void;
  539. /**
  540. * To compare floating point numbers, you can use toBeGreaterThanOrEqual.
  541. */
  542. toBeGreaterThanOrEqual(number: number): void;
  543. /**
  544. * To compare floating point numbers, you can use toBeLessThan.
  545. */
  546. toBeLessThan(number: number): void;
  547. /**
  548. * To compare floating point numbers, you can use toBeLessThanOrEqual.
  549. */
  550. toBeLessThanOrEqual(number: number): void;
  551. /**
  552. * Use .toBeInstanceOf(Class) to check that an object is an instance of a
  553. * class.
  554. */
  555. toBeInstanceOf(cls: Class<*>): void;
  556. /**
  557. * .toBeNull() is the same as .toBe(null) but the error messages are a bit
  558. * nicer.
  559. */
  560. toBeNull(): void;
  561. /**
  562. * Use .toBeTruthy when you don't care what a value is, you just want to
  563. * ensure a value is true in a boolean context.
  564. */
  565. toBeTruthy(): void;
  566. /**
  567. * Use .toBeUndefined to check that a variable is undefined.
  568. */
  569. toBeUndefined(): void;
  570. /**
  571. * Use .toContain when you want to check that an item is in a list. For
  572. * testing the items in the list, this uses ===, a strict equality check.
  573. */
  574. toContain(item: any): void;
  575. /**
  576. * Use .toContainEqual when you want to check that an item is in a list. For
  577. * testing the items in the list, this matcher recursively checks the
  578. * equality of all fields, rather than checking for object identity.
  579. */
  580. toContainEqual(item: any): void;
  581. /**
  582. * Use .toEqual when you want to check that two objects have the same value.
  583. * This matcher recursively checks the equality of all fields, rather than
  584. * checking for object identity.
  585. */
  586. toEqual(value: any): void;
  587. /**
  588. * Use .toHaveBeenCalled to ensure that a mock function got called.
  589. */
  590. toHaveBeenCalled(): void;
  591. toBeCalled(): void;
  592. /**
  593. * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
  594. * number of times.
  595. */
  596. toHaveBeenCalledTimes(number: number): void;
  597. toBeCalledTimes(number: number): void;
  598. /**
  599. *
  600. */
  601. toHaveBeenNthCalledWith(nthCall: number, ...args: Array<any>): void;
  602. nthCalledWith(nthCall: number, ...args: Array<any>): void;
  603. /**
  604. *
  605. */
  606. toHaveReturned(): void;
  607. toReturn(): void;
  608. /**
  609. *
  610. */
  611. toHaveReturnedTimes(number: number): void;
  612. toReturnTimes(number: number): void;
  613. /**
  614. *
  615. */
  616. toHaveReturnedWith(value: any): void;
  617. toReturnWith(value: any): void;
  618. /**
  619. *
  620. */
  621. toHaveLastReturnedWith(value: any): void;
  622. lastReturnedWith(value: any): void;
  623. /**
  624. *
  625. */
  626. toHaveNthReturnedWith(nthCall: number, value: any): void;
  627. nthReturnedWith(nthCall: number, value: any): void;
  628. /**
  629. * Use .toHaveBeenCalledWith to ensure that a mock function was called with
  630. * specific arguments.
  631. */
  632. toHaveBeenCalledWith(...args: Array<any>): void;
  633. toBeCalledWith(...args: Array<any>): void;
  634. /**
  635. * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called
  636. * with specific arguments.
  637. */
  638. toHaveBeenLastCalledWith(...args: Array<any>): void;
  639. lastCalledWith(...args: Array<any>): void;
  640. /**
  641. * Check that an object has a .length property and it is set to a certain
  642. * numeric value.
  643. */
  644. toHaveLength(number: number): void;
  645. /**
  646. *
  647. */
  648. toHaveProperty(propPath: string, value?: any): void;
  649. /**
  650. * Use .toMatch to check that a string matches a regular expression or string.
  651. */
  652. toMatch(regexpOrString: RegExp | string): void;
  653. /**
  654. * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
  655. */
  656. toMatchObject(object: Object | Array<Object>): void;
  657. /**
  658. * Use .toStrictEqual to check that a javascript object matches a subset of the properties of an object.
  659. */
  660. toStrictEqual(value: any): void;
  661. /**
  662. * This ensures that an Object matches the most recent snapshot.
  663. */
  664. toMatchSnapshot(
  665. propertyMatchers?: {[key: string]: JestAsymmetricEqualityType, ...},
  666. name?: string,
  667. ): void;
  668. /**
  669. * This ensures that an Object matches the most recent snapshot.
  670. */
  671. toMatchSnapshot(name: string): void;
  672. toMatchInlineSnapshot(snapshot?: string): void;
  673. toMatchInlineSnapshot(
  674. propertyMatchers?: {[key: string]: JestAsymmetricEqualityType, ...},
  675. snapshot?: string,
  676. ): void;
  677. /**
  678. * Use .toThrow to test that a function throws when it is called.
  679. * If you want to test that a specific error gets thrown, you can provide an
  680. * argument to toThrow. The argument can be a string for the error message,
  681. * a class for the error, or a regex that should match the error.
  682. *
  683. * Alias: .toThrowError
  684. */
  685. toThrow(message?: string | Error | Class<Error> | RegExp): void;
  686. toThrowError(message?: string | Error | Class<Error> | RegExp): void;
  687. /**
  688. * Use .toThrowErrorMatchingSnapshot to test that a function throws a error
  689. * matching the most recent snapshot when it is called.
  690. */
  691. toThrowErrorMatchingSnapshot(): void;
  692. toThrowErrorMatchingInlineSnapshot(snapshot?: string): void;
  693. }
  694. type JestObjectType = {
  695. /**
  696. * Disables automatic mocking in the module loader.
  697. *
  698. * After this method is called, all `require()`s will return the real
  699. * versions of each module (rather than a mocked version).
  700. */
  701. disableAutomock(): JestObjectType,
  702. /**
  703. * An un-hoisted version of disableAutomock
  704. */
  705. autoMockOff(): JestObjectType,
  706. /**
  707. * Enables automatic mocking in the module loader.
  708. */
  709. enableAutomock(): JestObjectType,
  710. /**
  711. * An un-hoisted version of enableAutomock
  712. */
  713. autoMockOn(): JestObjectType,
  714. /**
  715. * Clears the mock.calls and mock.instances properties of all mocks.
  716. * Equivalent to calling .mockClear() on every mocked function.
  717. */
  718. clearAllMocks(): JestObjectType,
  719. /**
  720. * Resets the state of all mocks. Equivalent to calling .mockReset() on every
  721. * mocked function.
  722. */
  723. resetAllMocks(): JestObjectType,
  724. /**
  725. * Restores all mocks back to their original value.
  726. */
  727. restoreAllMocks(): JestObjectType,
  728. /**
  729. * Removes any pending timers from the timer system.
  730. */
  731. clearAllTimers(): void,
  732. /**
  733. * The same as `mock` but not moved to the top of the expectation by
  734. * babel-jest.
  735. */
  736. doMock(moduleName: string, moduleFactory?: any): JestObjectType,
  737. /**
  738. * The same as `unmock` but not moved to the top of the expectation by
  739. * babel-jest.
  740. */
  741. dontMock(moduleName: string): JestObjectType,
  742. /**
  743. * Returns a new, unused mock function. Optionally takes a mock
  744. * implementation.
  745. */
  746. fn<TArguments: $ReadOnlyArray<mixed>, TReturn>(
  747. implementation?: (...args: TArguments) => TReturn,
  748. ): JestMockFn<TArguments, TReturn>,
  749. /**
  750. * Determines if the given function is a mocked function.
  751. */
  752. isMockFunction(fn: Function): boolean,
  753. /**
  754. * Given the name of a module, use the automatic mocking system to generate a
  755. * mocked version of the module for you.
  756. */
  757. genMockFromModule(moduleName: string): any,
  758. /**
  759. * Mocks a module with an auto-mocked version when it is being required.
  760. *
  761. * The second argument can be used to specify an explicit module factory that
  762. * is being run instead of using Jest's automocking feature.
  763. *
  764. * The third argument can be used to create virtual mocks -- mocks of modules
  765. * that don't exist anywhere in the system.
  766. */
  767. mock(
  768. moduleName: string,
  769. moduleFactory?: any,
  770. options?: Object,
  771. ): JestObjectType,
  772. /**
  773. * Returns the actual module instead of a mock, bypassing all checks on
  774. * whether the module should receive a mock implementation or not.
  775. */
  776. requireActual<T>(m: $Flow$ModuleRef<T> | string): T,
  777. /**
  778. * Returns a mock module instead of the actual module, bypassing all checks
  779. * on whether the module should be required normally or not.
  780. */
  781. requireMock(moduleName: string): any,
  782. /**
  783. * Resets the module registry - the cache of all required modules. This is
  784. * useful to isolate modules where local state might conflict between tests.
  785. */
  786. resetModules(): JestObjectType,
  787. /**
  788. * Exhausts the micro-task queue (usually interfaced in node via
  789. * process.nextTick).
  790. */
  791. runAllTicks(): void,
  792. /**
  793. * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
  794. * setInterval(), and setImmediate()).
  795. */
  796. runAllTimers(): void,
  797. /**
  798. * Exhausts all tasks queued by setImmediate().
  799. */
  800. runAllImmediates(): void,
  801. /**
  802. * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
  803. * or setInterval() and setImmediate()).
  804. */
  805. advanceTimersByTime(msToRun: number): void,
  806. /**
  807. * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
  808. * or setInterval() and setImmediate()).
  809. *
  810. * Renamed to `advanceTimersByTime`.
  811. */
  812. runTimersToTime(msToRun: number): void,
  813. /**
  814. * Executes only the macro-tasks that are currently pending (i.e., only the
  815. * tasks that have been queued by setTimeout() or setInterval() up to this
  816. * point)
  817. */
  818. runOnlyPendingTimers(): void,
  819. /**
  820. * Explicitly supplies the mock object that the module system should return
  821. * for the specified module. Note: It is recommended to use jest.mock()
  822. * instead.
  823. */
  824. setMock(moduleName: string, moduleExports: any): JestObjectType,
  825. /**
  826. * Indicates that the module system should never return a mocked version of
  827. * the specified module from require() (e.g. that it should always return the
  828. * real module).
  829. */
  830. unmock(moduleName: string): JestObjectType,
  831. /**
  832. * Instructs Jest to use fake versions of the standard timer functions
  833. * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
  834. * setImmediate and clearImmediate).
  835. */
  836. useFakeTimers(): JestObjectType,
  837. /**
  838. * Instructs Jest to use the real versions of the standard timer functions.
  839. */
  840. useRealTimers(): JestObjectType,
  841. /**
  842. * Creates a mock function similar to jest.fn but also tracks calls to
  843. * object[methodName].
  844. */
  845. spyOn(
  846. object: Object,
  847. methodName: string,
  848. accessType?: 'get' | 'set',
  849. ): JestMockFn<any, any>,
  850. /**
  851. * Set the default timeout interval for tests and before/after hooks in milliseconds.
  852. * Note: The default timeout interval is 5 seconds if this method is not called.
  853. */
  854. setTimeout(timeout: number): JestObjectType,
  855. ...
  856. };
  857. type JestSpyType = {
  858. calls: JestCallsType,
  859. ...
  860. };
  861. /** Runs this function after every test inside this context */
  862. declare function afterEach(
  863. fn: (done: () => void) => ?Promise<mixed>,
  864. timeout?: number,
  865. ): void;
  866. /** Runs this function before every test inside this context */
  867. declare function beforeEach(
  868. fn: (done: () => void) => ?Promise<mixed>,
  869. timeout?: number,
  870. ): void;
  871. /** Runs this function after all tests have finished inside this context */
  872. declare function afterAll(
  873. fn: (done: () => void) => ?Promise<mixed>,
  874. timeout?: number,
  875. ): void;
  876. /** Runs this function before any tests have started inside this context */
  877. declare function beforeAll(
  878. fn: (done: () => void) => ?Promise<mixed>,
  879. timeout?: number,
  880. ): void;
  881. /** A context for grouping tests together */
  882. declare var describe: {
  883. /**
  884. * Creates a block that groups together several related tests in one "test suite"
  885. */
  886. (name: JestTestName, fn: () => void): void,
  887. /**
  888. * Only run this describe block
  889. */
  890. only(name: JestTestName, fn: () => void): void,
  891. /**
  892. * Skip running this describe block
  893. */
  894. skip(name: JestTestName, fn: () => void): void,
  895. /**
  896. * each runs this test against array of argument arrays per each run
  897. *
  898. * @param {table} table of Test
  899. */
  900. each<TArguments: Array<mixed> | mixed>(
  901. table: $ReadOnlyArray<TArguments>,
  902. ): (
  903. name: JestTestName,
  904. fn?: (...args: TArguments) => ?Promise<mixed>,
  905. ) => void,
  906. ...
  907. };
  908. /** An individual test unit */
  909. declare var it: {
  910. /**
  911. * An individual test unit
  912. *
  913. * @param {JestTestName} Name of Test
  914. * @param {Function} Test
  915. * @param {number} Timeout for the test, in milliseconds.
  916. */
  917. (
  918. name: JestTestName,
  919. fn?: (done: () => void) => ?Promise<mixed>,
  920. timeout?: number,
  921. ): void,
  922. /**
  923. * each runs this test against array of argument arrays per each run
  924. *
  925. * @param {table} table of Test
  926. */
  927. each<TArguments: Array<mixed> | mixed>(
  928. table: $ReadOnlyArray<TArguments>,
  929. ): (
  930. name: JestTestName,
  931. fn?: (...args: TArguments) => ?Promise<mixed>,
  932. ) => void,
  933. /**
  934. * Only run this test
  935. *
  936. * @param {JestTestName} Name of Test
  937. * @param {Function} Test
  938. * @param {number} Timeout for the test, in milliseconds.
  939. */
  940. only(
  941. name: JestTestName,
  942. fn?: (done: () => void) => ?Promise<mixed>,
  943. timeout?: number,
  944. ): {
  945. each<TArguments: Array<mixed> | mixed>(
  946. table: $ReadOnlyArray<TArguments>,
  947. ): (
  948. name: JestTestName,
  949. fn?: (...args: TArguments) => ?Promise<mixed>,
  950. ) => void,
  951. ...
  952. },
  953. /**
  954. * Skip running this test
  955. *
  956. * @param {JestTestName} Name of Test
  957. * @param {Function} Test
  958. * @param {number} Timeout for the test, in milliseconds.
  959. */
  960. skip(
  961. name: JestTestName,
  962. fn?: (done: () => void) => ?Promise<mixed>,
  963. timeout?: number,
  964. ): void,
  965. /**
  966. * Run the test concurrently
  967. *
  968. * @param {JestTestName} Name of Test
  969. * @param {Function} Test
  970. * @param {number} Timeout for the test, in milliseconds.
  971. */
  972. concurrent(
  973. name: JestTestName,
  974. fn?: (done: () => void) => ?Promise<mixed>,
  975. timeout?: number,
  976. ): void,
  977. ...
  978. };
  979. declare function fit(
  980. name: JestTestName,
  981. fn: (done: () => void) => ?Promise<mixed>,
  982. timeout?: number,
  983. ): void;
  984. /** An individual test unit */
  985. declare var test: typeof it;
  986. /** A disabled group of tests */
  987. declare var xdescribe: typeof describe;
  988. /** A focused group of tests */
  989. declare var fdescribe: typeof describe;
  990. /** A disabled individual test */
  991. declare var xit: typeof it;
  992. /** A disabled individual test */
  993. declare var xtest: typeof it;
  994. type JestPrettyFormatColors = {
  995. comment: {close: string, open: string, ...},
  996. content: {close: string, open: string, ...},
  997. prop: {close: string, open: string, ...},
  998. tag: {close: string, open: string, ...},
  999. value: {close: string, open: string, ...},
  1000. ...
  1001. };
  1002. type JestPrettyFormatIndent = string => string;
  1003. type JestPrettyFormatPrint = any => string;
  1004. type JestPrettyFormatOptions = {|
  1005. callToJSON: boolean,
  1006. edgeSpacing: string,
  1007. escapeRegex: boolean,
  1008. highlight: boolean,
  1009. indent: number,
  1010. maxDepth: number,
  1011. min: boolean,
  1012. plugins: JestPrettyFormatPlugins,
  1013. printFunctionName: boolean,
  1014. spacing: string,
  1015. theme: {|
  1016. comment: string,
  1017. content: string,
  1018. prop: string,
  1019. tag: string,
  1020. value: string,
  1021. |},
  1022. |};
  1023. type JestPrettyFormatPlugin = {
  1024. print: (
  1025. val: any,
  1026. serialize: JestPrettyFormatPrint,
  1027. indent: JestPrettyFormatIndent,
  1028. opts: JestPrettyFormatOptions,
  1029. colors: JestPrettyFormatColors,
  1030. ) => string,
  1031. test: any => boolean,
  1032. ...
  1033. };
  1034. type JestPrettyFormatPlugins = Array<JestPrettyFormatPlugin>;
  1035. /** The expect function is used every time you want to test a value */
  1036. declare var expect: {
  1037. /** The object that you want to make assertions against */
  1038. (
  1039. value: any,
  1040. ): JestExpectType &
  1041. JestPromiseType &
  1042. EnzymeMatchersType &
  1043. DomTestingLibraryType &
  1044. JestJQueryMatchersType &
  1045. JestStyledComponentsMatchersType &
  1046. JestExtendedMatchersType,
  1047. /** Add additional Jasmine matchers to Jest's roster */
  1048. extend(matchers: {[name: string]: JestMatcher, ...}): void,
  1049. /** Add a module that formats application-specific data structures. */
  1050. addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void,
  1051. assertions(expectedAssertions: number): void,
  1052. hasAssertions(): void,
  1053. any(value: mixed): JestAsymmetricEqualityType,
  1054. anything(): any,
  1055. arrayContaining(value: $ReadOnlyArray<mixed>): Array<mixed>,
  1056. objectContaining(value: Object): Object,
  1057. /** Matches any received string that contains the exact expected string. */
  1058. stringContaining(value: string): string,
  1059. stringMatching(value: string | RegExp): string,
  1060. not: {
  1061. arrayContaining: (value: $ReadOnlyArray<mixed>) => Array<mixed>,
  1062. objectContaining: (value: {...}) => Object,
  1063. stringContaining: (value: string) => string,
  1064. stringMatching: (value: string | RegExp) => string,
  1065. ...
  1066. },
  1067. ...
  1068. };
  1069. // TODO handle return type
  1070. // http://jasmine.github.io/2.4/introduction.html#section-Spies
  1071. declare function spyOn(value: mixed, method: string): Object;
  1072. /** Holds all functions related to manipulating test runner */
  1073. declare var jest: JestObjectType;
  1074. /**
  1075. * https://jasmine.github.io/2.4/custom_reporter.html
  1076. */
  1077. type JasmineReporter = {
  1078. jasmineStarted?: (suiteInfo: mixed) => void,
  1079. suiteStarted?: (result: mixed) => void,
  1080. specStarted?: (result: mixed) => void,
  1081. specDone?: (result: mixed) => void,
  1082. suiteDone?: (result: mixed) => void,
  1083. ...
  1084. };
  1085. /**
  1086. * The global Jasmine object, this is generally not exposed as the public API,
  1087. * using features inside here could break in later versions of Jest.
  1088. */
  1089. declare var jasmine: {
  1090. DEFAULT_TIMEOUT_INTERVAL: number,
  1091. any(value: mixed): JestAsymmetricEqualityType,
  1092. anything(): any,
  1093. arrayContaining(value: $ReadOnlyArray<mixed>): Array<mixed>,
  1094. clock(): JestClockType,
  1095. createSpy(name: string): JestSpyType,
  1096. createSpyObj(
  1097. baseName: string,
  1098. methodNames: Array<string>,
  1099. ): {[methodName: string]: JestSpyType, ...},
  1100. getEnv(): {addReporter: (jasmineReporter: JasmineReporter) => void, ...},
  1101. objectContaining(value: Object): Object,
  1102. stringMatching(value: string): string,
  1103. ...
  1104. };