From ea5b9c1371b136c6292baf9ed86e3a068340b273 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 7 Apr 2018 13:52:33 -0500 Subject: [PATCH] Add Mock A Function With Return Values Using Jest as a javascript til --- README.md | 3 +- ...-function-with-return-values-using-jest.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 javascript/mock-a-function-with-return-values-using-jest.md diff --git a/README.md b/README.md index 1909234..9312d59 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/javascript/mock-a-function-with-return-values-using-jest.md b/javascript/mock-a-function-with-return-values-using-jest.md new file mode 100644 index 0000000..99bcb9a --- /dev/null +++ b/javascript/mock-a-function-with-return-values-using-jest.md @@ -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 + +``` + +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`.