1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Mock A Function With Return Values Using Jest as a javascript til

This commit is contained in:
jbranchaud
2018-04-07 13:52:33 -05:00
parent e49d8b7530
commit ea5b9c1371
2 changed files with 41 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_657 TILs and counting..._
_658 TILs and counting..._
---
@@ -246,6 +246,7 @@ _657 TILs and counting..._
- [Link A JavaScript Package Locally](javascript/link-a-javascript-package-locally.md)
- [List Top-Level NPM Dependencies](javascript/list-top-level-npm-dependencies.md)
- [Matching Multiple Values In A Switch Statement](javascript/matching-multiple-values-in-a-switch-statement.md)
- [Mock A Function With Return Values Using Jest](javascript/mock-a-function-with-return-values-using-jest.md)
- [New Dates Can Take Out Of Bounds Values](javascript/new-dates-can-take-out-of-bounds-values.md)
- [Numbers Are Empty](javascript/numbers-are-empty.md)
- [Object Initialization With Shorthand Property Names](javascript/object-initialization-with-shorthand-property-names.md)

View File

@@ -0,0 +1,39 @@
# Mock A Function With Return Values Using Jest
[Jest](https://facebook.github.io/jest/) provides a collection of utilities
for working with mocked functions. To create a mock function, do:
```javascript
jest.fn()
// assign it to a variable
const fakeFunc = jest.fn();
// pass it as a prop
<SpecialInput handleChange={jest.fn()} />
```
A mocked function can then be attributed with a return value.
```javascript
const fakeFunc = jest.fn();
fakeFunc.mockReturnValue("hello");
fakeFunc(); // => "hello"
```
The
[`mockReturnValue()`](https://facebook.github.io/jest/docs/en/mock-function-api.html#mockfnmockreturnvaluevalue)
function ensures that the value is returned whenever your function is
called.
We can also limit the return value to occurring just once.
```javascript
const fakeFunc = jest.fn();
fakeFunc.mockReturnValueOnce("hello");
fakeFunc(); // => "hello"
fakeFunc(); // => null
```
[`mockReturnValueOnce()`](https://facebook.github.io/jest/docs/en/mock-function-api.html#mockfnmockreturnvalueoncevalue)
ensures the value is returned once and all subsequent calls yield `null`.