|
| 1 | +# Mock A Function That A Component Imports |
| 2 | + |
| 3 | +You have a component that relies on an imported function, |
| 4 | +`isAuthenticated()`. |
| 5 | + |
| 6 | +```javascript |
| 7 | +// MyComponent.js |
| 8 | +import React from 'react'; |
| 9 | +import { isAuthenticated } from './authentication'; |
| 10 | + |
| 11 | +const MyComponent = (props) => { |
| 12 | + if (isAuthenticated()) { |
| 13 | + return (<div>{/* ... */}</div>); |
| 14 | + } else { |
| 15 | + return (<div>Not authenticated</div>); |
| 16 | + } |
| 17 | +}; |
| 18 | +``` |
| 19 | + |
| 20 | +You'd like to test that component without having to manage the |
| 21 | +authentication of a user. One option is to mock out that function. This can |
| 22 | +be done with some help from [`jest.fn()` and the `mock.mockReturnValue()` |
| 23 | +function](https://github.com/jbranchaud/til/blob/master/javascript/mock-a-function-with-return-values-using-jest.md). |
| 24 | + |
| 25 | +```javascript |
| 26 | +// MyComponent.test.js |
| 27 | +// ... various testing imports |
| 28 | + |
| 29 | +import * as authModules from './authentication'; |
| 30 | + |
| 31 | +it('renders the component', () => { |
| 32 | + authModules.isAuthenticated = jest.fn().mockReturnValue(true); |
| 33 | + |
| 34 | + const wrapper = shallow(<MyComponent />); |
| 35 | + expect(toJson(wrapper)).toMatchSnapshot(); |
| 36 | +}); |
| 37 | +``` |
| 38 | + |
| 39 | +By importing the same module and functions used by `MyComponent`, we are |
| 40 | +then able to replace them (specifically, `isAuthenticated`) with a mocked |
| 41 | +version of the function that returns whatever value we'd like. As |
| 42 | +`MyComponent` is being rendered, it will invoked our mocked version of |
| 43 | +`isAuthenticated` instead of the actual one. |
| 44 | + |
| 45 | +You could test the other direction like so: |
| 46 | + |
| 47 | +```javascript |
| 48 | +authModules.isAuthenticated = jest.fn().mockReturnValue(false); |
| 49 | +``` |
0 commit comments