UNPKG

18.8 kBJavaScriptView Raw
1// flow-typed signature: ebbcd423b1fcd29d6804fca91bb68879
2// flow-typed version: 7b9f6d2713/jest_v22.x.x/flow_>=v0.39.x
3
4type JestMockFn<TArguments: $ReadOnlyArray<*>, TReturn> = {
5 (...args: TArguments): TReturn,
6 /**
7 * An object for introspecting mock calls
8 */
9 mock: {
10 /**
11 * An array that represents all calls that have been made into this mock
12 * function. Each call is represented by an array of arguments that were
13 * passed during the call.
14 */
15 calls: Array<TArguments>,
16 /**
17 * An array that contains all the object instances that have been
18 * instantiated from this mock function.
19 */
20 instances: Array<TReturn>
21 },
22 /**
23 * Resets all information stored in the mockFn.mock.calls and
24 * mockFn.mock.instances arrays. Often this is useful when you want to clean
25 * up a mock's usage data between two assertions.
26 */
27 mockClear(): void,
28 /**
29 * Resets all information stored in the mock. This is useful when you want to
30 * completely restore a mock back to its initial state.
31 */
32 mockReset(): void,
33 /**
34 * Removes the mock and restores the initial implementation. This is useful
35 * when you want to mock functions in certain test cases and restore the
36 * original implementation in others. Beware that mockFn.mockRestore only
37 * works when mock was created with jest.spyOn. Thus you have to take care of
38 * restoration yourself when manually assigning jest.fn().
39 */
40 mockRestore(): void,
41 /**
42 * Accepts a function that should be used as the implementation of the mock.
43 * The mock itself will still record all calls that go into and instances
44 * that come from itself -- the only difference is that the implementation
45 * will also be executed when the mock is called.
46 */
47 mockImplementation(
48 fn: (...args: TArguments) => TReturn
49 ): JestMockFn<TArguments, TReturn>,
50 /**
51 * Accepts a function that will be used as an implementation of the mock for
52 * one call to the mocked function. Can be chained so that multiple function
53 * calls produce different results.
54 */
55 mockImplementationOnce(
56 fn: (...args: TArguments) => TReturn
57 ): JestMockFn<TArguments, TReturn>,
58 /**
59 * Just a simple sugar function for returning `this`
60 */
61 mockReturnThis(): void,
62 /**
63 * Deprecated: use jest.fn(() => value) instead
64 */
65 mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,
66 /**
67 * Sugar for only returning a value once inside your mock
68 */
69 mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>
70};
71
72type JestAsymmetricEqualityType = {
73 /**
74 * A custom Jasmine equality tester
75 */
76 asymmetricMatch(value: mixed): boolean
77};
78
79type JestCallsType = {
80 allArgs(): mixed,
81 all(): mixed,
82 any(): boolean,
83 count(): number,
84 first(): mixed,
85 mostRecent(): mixed,
86 reset(): void
87};
88
89type JestClockType = {
90 install(): void,
91 mockDate(date: Date): void,
92 tick(milliseconds?: number): void,
93 uninstall(): void
94};
95
96type JestMatcherResult = {
97 message?: string | (() => string),
98 pass: boolean
99};
100
101type JestMatcher = (actual: any, expected: any) => JestMatcherResult;
102
103type JestPromiseType = {
104 /**
105 * Use rejects to unwrap the reason of a rejected promise so any other
106 * matcher can be chained. If the promise is fulfilled the assertion fails.
107 */
108 rejects: JestExpectType,
109 /**
110 * Use resolves to unwrap the value of a fulfilled promise so any other
111 * matcher can be chained. If the promise is rejected the assertion fails.
112 */
113 resolves: JestExpectType
114};
115
116/**
117 * Jest allows functions and classes to be used as test names in test() and
118 * describe()
119 */
120type JestTestName = string | Function;
121
122/**
123 * Plugin: jest-enzyme
124 */
125type EnzymeMatchersType = {
126 toBeChecked(): void,
127 toBeDisabled(): void,
128 toBeEmpty(): void,
129 toBeEmptyRender(): void,
130 toBePresent(): void,
131 toContainReact(element: React$Element<any>): void,
132 toExist(): void,
133 toHaveClassName(className: string): void,
134 toHaveHTML(html: string): void,
135 toHaveProp: ((propKey: string, propValue?: any) => void) &
136 ((props: Object) => void),
137 toHaveRef(refName: string): void,
138 toHaveState: ((stateKey: string, stateValue?: any) => void) &
139 ((state: Object) => void),
140 toHaveStyle: ((styleKey: string, styleValue?: any) => void) &
141 ((style: Object) => void),
142 toHaveTagName(tagName: string): void,
143 toHaveText(text: string): void,
144 toIncludeText(text: string): void,
145 toHaveValue(value: any): void,
146 toMatchElement(element: React$Element<any>): void,
147 toMatchSelector(selector: string): void
148};
149
150type JestExpectType = {
151 not: JestExpectType & EnzymeMatchersType,
152 /**
153 * If you have a mock function, you can use .lastCalledWith to test what
154 * arguments it was last called with.
155 */
156 lastCalledWith(...args: Array<any>): void,
157 /**
158 * toBe just checks that a value is what you expect. It uses === to check
159 * strict equality.
160 */
161 toBe(value: any): void,
162 /**
163 * Use .toHaveBeenCalled to ensure that a mock function got called.
164 */
165 toBeCalled(): void,
166 /**
167 * Use .toBeCalledWith to ensure that a mock function was called with
168 * specific arguments.
169 */
170 toBeCalledWith(...args: Array<any>): void,
171 /**
172 * Using exact equality with floating point numbers is a bad idea. Rounding
173 * means that intuitive things fail.
174 */
175 toBeCloseTo(num: number, delta: any): void,
176 /**
177 * Use .toBeDefined to check that a variable is not undefined.
178 */
179 toBeDefined(): void,
180 /**
181 * Use .toBeFalsy when you don't care what a value is, you just want to
182 * ensure a value is false in a boolean context.
183 */
184 toBeFalsy(): void,
185 /**
186 * To compare floating point numbers, you can use toBeGreaterThan.
187 */
188 toBeGreaterThan(number: number): void,
189 /**
190 * To compare floating point numbers, you can use toBeGreaterThanOrEqual.
191 */
192 toBeGreaterThanOrEqual(number: number): void,
193 /**
194 * To compare floating point numbers, you can use toBeLessThan.
195 */
196 toBeLessThan(number: number): void,
197 /**
198 * To compare floating point numbers, you can use toBeLessThanOrEqual.
199 */
200 toBeLessThanOrEqual(number: number): void,
201 /**
202 * Use .toBeInstanceOf(Class) to check that an object is an instance of a
203 * class.
204 */
205 toBeInstanceOf(cls: Class<*>): void,
206 /**
207 * .toBeNull() is the same as .toBe(null) but the error messages are a bit
208 * nicer.
209 */
210 toBeNull(): void,
211 /**
212 * Use .toBeTruthy when you don't care what a value is, you just want to
213 * ensure a value is true in a boolean context.
214 */
215 toBeTruthy(): void,
216 /**
217 * Use .toBeUndefined to check that a variable is undefined.
218 */
219 toBeUndefined(): void,
220 /**
221 * Use .toContain when you want to check that an item is in a list. For
222 * testing the items in the list, this uses ===, a strict equality check.
223 */
224 toContain(item: any): void,
225 /**
226 * Use .toContainEqual when you want to check that an item is in a list. For
227 * testing the items in the list, this matcher recursively checks the
228 * equality of all fields, rather than checking for object identity.
229 */
230 toContainEqual(item: any): void,
231 /**
232 * Use .toEqual when you want to check that two objects have the same value.
233 * This matcher recursively checks the equality of all fields, rather than
234 * checking for object identity.
235 */
236 toEqual(value: any): void,
237 /**
238 * Use .toHaveBeenCalled to ensure that a mock function got called.
239 */
240 toHaveBeenCalled(): void,
241 /**
242 * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
243 * number of times.
244 */
245 toHaveBeenCalledTimes(number: number): void,
246 /**
247 * Use .toHaveBeenCalledWith to ensure that a mock function was called with
248 * specific arguments.
249 */
250 toHaveBeenCalledWith(...args: Array<any>): void,
251 /**
252 * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called
253 * with specific arguments.
254 */
255 toHaveBeenLastCalledWith(...args: Array<any>): void,
256 /**
257 * Check that an object has a .length property and it is set to a certain
258 * numeric value.
259 */
260 toHaveLength(number: number): void,
261 /**
262 *
263 */
264 toHaveProperty(propPath: string, value?: any): void,
265 /**
266 * Use .toMatch to check that a string matches a regular expression or string.
267 */
268 toMatch(regexpOrString: RegExp | string): void,
269 /**
270 * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
271 */
272 toMatchObject(object: Object | Array<Object>): void,
273 /**
274 * This ensures that a React component matches the most recent snapshot.
275 */
276 toMatchSnapshot(name?: string): void,
277 /**
278 * Use .toThrow to test that a function throws when it is called.
279 * If you want to test that a specific error gets thrown, you can provide an
280 * argument to toThrow. The argument can be a string for the error message,
281 * a class for the error, or a regex that should match the error.
282 *
283 * Alias: .toThrowError
284 */
285 toThrow(message?: string | Error | Class<Error> | RegExp): void,
286 toThrowError(message?: string | Error | Class<Error> | RegExp): void,
287 /**
288 * Use .toThrowErrorMatchingSnapshot to test that a function throws a error
289 * matching the most recent snapshot when it is called.
290 */
291 toThrowErrorMatchingSnapshot(): void
292};
293
294type JestObjectType = {
295 /**
296 * Disables automatic mocking in the module loader.
297 *
298 * After this method is called, all `require()`s will return the real
299 * versions of each module (rather than a mocked version).
300 */
301 disableAutomock(): JestObjectType,
302 /**
303 * An un-hoisted version of disableAutomock
304 */
305 autoMockOff(): JestObjectType,
306 /**
307 * Enables automatic mocking in the module loader.
308 */
309 enableAutomock(): JestObjectType,
310 /**
311 * An un-hoisted version of enableAutomock
312 */
313 autoMockOn(): JestObjectType,
314 /**
315 * Clears the mock.calls and mock.instances properties of all mocks.
316 * Equivalent to calling .mockClear() on every mocked function.
317 */
318 clearAllMocks(): JestObjectType,
319 /**
320 * Resets the state of all mocks. Equivalent to calling .mockReset() on every
321 * mocked function.
322 */
323 resetAllMocks(): JestObjectType,
324 /**
325 * Restores all mocks back to their original value.
326 */
327 restoreAllMocks(): JestObjectType,
328 /**
329 * Removes any pending timers from the timer system.
330 */
331 clearAllTimers(): void,
332 /**
333 * The same as `mock` but not moved to the top of the expectation by
334 * babel-jest.
335 */
336 doMock(moduleName: string, moduleFactory?: any): JestObjectType,
337 /**
338 * The same as `unmock` but not moved to the top of the expectation by
339 * babel-jest.
340 */
341 dontMock(moduleName: string): JestObjectType,
342 /**
343 * Returns a new, unused mock function. Optionally takes a mock
344 * implementation.
345 */
346 fn<TArguments: $ReadOnlyArray<*>, TReturn>(
347 implementation?: (...args: TArguments) => TReturn
348 ): JestMockFn<TArguments, TReturn>,
349 /**
350 * Determines if the given function is a mocked function.
351 */
352 isMockFunction(fn: Function): boolean,
353 /**
354 * Given the name of a module, use the automatic mocking system to generate a
355 * mocked version of the module for you.
356 */
357 genMockFromModule(moduleName: string): any,
358 /**
359 * Mocks a module with an auto-mocked version when it is being required.
360 *
361 * The second argument can be used to specify an explicit module factory that
362 * is being run instead of using Jest's automocking feature.
363 *
364 * The third argument can be used to create virtual mocks -- mocks of modules
365 * that don't exist anywhere in the system.
366 */
367 mock(
368 moduleName: string,
369 moduleFactory?: any,
370 options?: Object
371 ): JestObjectType,
372 /**
373 * Returns the actual module instead of a mock, bypassing all checks on
374 * whether the module should receive a mock implementation or not.
375 */
376 requireActual(moduleName: string): any,
377 /**
378 * Returns a mock module instead of the actual module, bypassing all checks
379 * on whether the module should be required normally or not.
380 */
381 requireMock(moduleName: string): any,
382 /**
383 * Resets the module registry - the cache of all required modules. This is
384 * useful to isolate modules where local state might conflict between tests.
385 */
386 resetModules(): JestObjectType,
387 /**
388 * Exhausts the micro-task queue (usually interfaced in node via
389 * process.nextTick).
390 */
391 runAllTicks(): void,
392 /**
393 * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
394 * setInterval(), and setImmediate()).
395 */
396 runAllTimers(): void,
397 /**
398 * Exhausts all tasks queued by setImmediate().
399 */
400 runAllImmediates(): void,
401 /**
402 * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
403 * or setInterval() and setImmediate()).
404 */
405 runTimersToTime(msToRun: number): void,
406 /**
407 * Executes only the macro-tasks that are currently pending (i.e., only the
408 * tasks that have been queued by setTimeout() or setInterval() up to this
409 * point)
410 */
411 runOnlyPendingTimers(): void,
412 /**
413 * Explicitly supplies the mock object that the module system should return
414 * for the specified module. Note: It is recommended to use jest.mock()
415 * instead.
416 */
417 setMock(moduleName: string, moduleExports: any): JestObjectType,
418 /**
419 * Indicates that the module system should never return a mocked version of
420 * the specified module from require() (e.g. that it should always return the
421 * real module).
422 */
423 unmock(moduleName: string): JestObjectType,
424 /**
425 * Instructs Jest to use fake versions of the standard timer functions
426 * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
427 * setImmediate and clearImmediate).
428 */
429 useFakeTimers(): JestObjectType,
430 /**
431 * Instructs Jest to use the real versions of the standard timer functions.
432 */
433 useRealTimers(): JestObjectType,
434 /**
435 * Creates a mock function similar to jest.fn but also tracks calls to
436 * object[methodName].
437 */
438 spyOn(object: Object, methodName: string): JestMockFn<any, any>,
439 /**
440 * Set the default timeout interval for tests and before/after hooks in milliseconds.
441 * Note: The default timeout interval is 5 seconds if this method is not called.
442 */
443 setTimeout(timeout: number): JestObjectType
444};
445
446type JestSpyType = {
447 calls: JestCallsType
448};
449
450/** Runs this function after every test inside this context */
451declare function afterEach(
452 fn: (done: () => void) => ?Promise<mixed>,
453 timeout?: number
454): void;
455/** Runs this function before every test inside this context */
456declare function beforeEach(
457 fn: (done: () => void) => ?Promise<mixed>,
458 timeout?: number
459): void;
460/** Runs this function after all tests have finished inside this context */
461declare function afterAll(
462 fn: (done: () => void) => ?Promise<mixed>,
463 timeout?: number
464): void;
465/** Runs this function before any tests have started inside this context */
466declare function beforeAll(
467 fn: (done: () => void) => ?Promise<mixed>,
468 timeout?: number
469): void;
470
471/** A context for grouping tests together */
472declare var describe: {
473 /**
474 * Creates a block that groups together several related tests in one "test suite"
475 */
476 (name: JestTestName, fn: () => void): void,
477
478 /**
479 * Only run this describe block
480 */
481 only(name: JestTestName, fn: () => void): void,
482
483 /**
484 * Skip running this describe block
485 */
486 skip(name: JestTestName, fn: () => void): void
487};
488
489/** An individual test unit */
490declare var it: {
491 /**
492 * An individual test unit
493 *
494 * @param {JestTestName} Name of Test
495 * @param {Function} Test
496 * @param {number} Timeout for the test, in milliseconds.
497 */
498 (
499 name: JestTestName,
500 fn?: (done: () => void) => ?Promise<mixed>,
501 timeout?: number
502 ): void,
503 /**
504 * Only run this test
505 *
506 * @param {JestTestName} Name of Test
507 * @param {Function} Test
508 * @param {number} Timeout for the test, in milliseconds.
509 */
510 only(
511 name: JestTestName,
512 fn?: (done: () => void) => ?Promise<mixed>,
513 timeout?: number
514 ): void,
515 /**
516 * Skip running this test
517 *
518 * @param {JestTestName} Name of Test
519 * @param {Function} Test
520 * @param {number} Timeout for the test, in milliseconds.
521 */
522 skip(
523 name: JestTestName,
524 fn?: (done: () => void) => ?Promise<mixed>,
525 timeout?: number
526 ): void,
527 /**
528 * Run the test concurrently
529 *
530 * @param {JestTestName} Name of Test
531 * @param {Function} Test
532 * @param {number} Timeout for the test, in milliseconds.
533 */
534 concurrent(
535 name: JestTestName,
536 fn?: (done: () => void) => ?Promise<mixed>,
537 timeout?: number
538 ): void
539};
540declare function fit(
541 name: JestTestName,
542 fn: (done: () => void) => ?Promise<mixed>,
543 timeout?: number
544): void;
545/** An individual test unit */
546declare var test: typeof it;
547/** A disabled group of tests */
548declare var xdescribe: typeof describe;
549/** A focused group of tests */
550declare var fdescribe: typeof describe;
551/** A disabled individual test */
552declare var xit: typeof it;
553/** A disabled individual test */
554declare var xtest: typeof it;
555
556/** The expect function is used every time you want to test a value */
557declare var expect: {
558 /** The object that you want to make assertions against */
559 (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType,
560 /** Add additional Jasmine matchers to Jest's roster */
561 extend(matchers: { [name: string]: JestMatcher }): void,
562 /** Add a module that formats application-specific data structures. */
563 addSnapshotSerializer(serializer: (input: Object) => string): void,
564 assertions(expectedAssertions: number): void,
565 hasAssertions(): void,
566 any(value: mixed): JestAsymmetricEqualityType,
567 anything(): any,
568 arrayContaining(value: Array<mixed>): Array<mixed>,
569 objectContaining(value: Object): Object,
570 /** Matches any received string that contains the exact expected string. */
571 stringContaining(value: string): string,
572 stringMatching(value: string | RegExp): string
573};
574
575// TODO handle return type
576// http://jasmine.github.io/2.4/introduction.html#section-Spies
577declare function spyOn(value: mixed, method: string): Object;
578
579/** Holds all functions related to manipulating test runner */
580declare var jest: JestObjectType;
581
582/**
583 * The global Jasmine object, this is generally not exposed as the public API,
584 * using features inside here could break in later versions of Jest.
585 */
586declare var jasmine: {
587 DEFAULT_TIMEOUT_INTERVAL: number,
588 any(value: mixed): JestAsymmetricEqualityType,
589 anything(): any,
590 arrayContaining(value: Array<mixed>): Array<mixed>,
591 clock(): JestClockType,
592 createSpy(name: string): JestSpyType,
593 createSpyObj(
594 baseName: string,
595 methodNames: Array<string>
596 ): { [methodName: string]: JestSpyType },
597 objectContaining(value: Object): Object,
598 stringMatching(value: string): string
599};